Reputation:
I have service like this :
getLastStatus(id): Observable<string> {
let url_detail = this.apiurl + `/${id}`;
return this.http.get<any>(url_detail, this.httpOptions).pipe(
map(data => {
var status = data['data'].reduce((item, curr) => {
return item.id < curr.id ? curr : item;
}).status.title;
return status;
}),
catchError(this.handleError)
);
}
getData(){
return this.http.get<DataModel[]>(this.apiurl, this.httpOptions).pipe(
tap(data=> {
data.map(d=>{
this.getLastStatus(d.id).subscribe(s=>{
d.status = s;
});
});
}),
catchError(this.handleError)
);
}
I want to update value of status from the result of json object. But, when I subscribe getData() like this, the value of status not updated.
this.myService.getData().subscribe(data=>{
console.log(data)
data.map(d=>{
console.log("status ", d.status) //value of status not updated
})
});
What's should i do with my code? Any suggestion?
Upvotes: 0
Views: 1160
Reputation: 31105
It appears the statuses are obtained asynchronously. You could avoid nested subscriptions using RxJS higher order mapping operator like switchMap
. And since you have a bunch of observables to trigger at once, you could use the RxJS forkJoin
function.
I'm also using JS destructuring to retain the properties of the object except to adjust or include the status
property.
Try the following
getData() {
return this.http.get<DataModel[]>(this.apiurl, this.httpOptions).pipe(
switchMap(data =>
forkJoin(
data.map(d =>
this.getLastStatus(d.id).pipe(
map(status => ({ ...d, d.status: status }))
)
)
)
),
catchError(this.handleError)
);
}
You could also refer here for more info on switchMap
operator and forkJoin
function.
Upvotes: 1