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
)
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.
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
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With