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


in service.component.js return observable of array of student http call. student object has property called age,

student.ts

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

service.componnet.js

getstudents (): observable< student[]>  

in studentmanagement.component.ts observer observable above, want sum age of students. know can put sum() in source (which less preferred, need display other info of students in page, such id, name ,individual age well.) or calculate _studentlist. besides these two, other way?

private _studentlist:student[]=[];      .subscribe(             returnedstudents => {               console.log(returnedstudents);               this._studentlist = returnedstudents;             },             erromsg => this._errormessage = erromsg           )  

you use map on observable return sum.

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

here reduce inner array sum of age property of students. have observable<number>, emit sum of ages.

if want display both:

getstudents (): observable< student[]> {    return this.http.get(/*...*/).share(); }  getagesum(): observable<number> {     return this.studentsobservable        .map(arr => arr.reduce((a, b) => + b.age, 0)); } 

we have call share here, observable becomes hot , doesn't http request twice.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -