Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - sum the values of a property in the Object sent from an observerable

in my service.component.js I return an observable of an array of Student from the http call. Student object has a property called age,

student.ts

export class Student {
  id: number;
  name: string;
  age:number;
}

service.componnet.js

getStudents (): Observable< Student[]> 

In the studentManagement.component.ts which is an observer to the observable above, I want to sum the age of the students. I know I can put a sum() in source (which is less preferred, as I also need to display other info of the Students in the page, such as id, name ,individual age as well.) or calculate it from _studentList. Besides these two, any other way?

private _studentList:Student[]=[];

    .subscribe(
            returnedStudents => {
              console.log(returnedStudents);
              this._studentList = returnedStudents;
            },
            erroMsg => this._errorMessage = erroMsg
          ) 
like image 367
Hammer Avatar asked Mar 13 '23 08:03

Hammer


2 Answers

You could use map on the Observable to return the sum.

getStudents().map(arr => arr.reduce((a, b) => a + b.age, 0));

Here we reduce the inner Array to the sum of the age property of the students. Now what we have is a Observable<number>, which will emit the sum of the ages.

If you want to display both:

getStudents (): Observable< Student[]> {
   return this.http.get(/*...*/).share();
}

getAgeSum(): Observable<number> {
    return this.studentsObservable
       .map(arr => arr.reduce((a, b) => a + b.age, 0));
}

We have to call share here, so that the Observable becomes hot and doesn't do the HTTP Request twice.

like image 157
Luka Jacobowitz Avatar answered Mar 19 '23 16:03

Luka Jacobowitz


You could use a map function that returns both student list and age sums. Something like that:

studentsObservable.map((students) => {
  return {
    ages: this.getAge(students),
    students: students
  };
});
like image 28
Thierry Templier Avatar answered Mar 19 '23 15:03

Thierry Templier