Issue
I am having trouble to figure out how I can update the result of one Observable with the result of another:
this._http.get<JSON>(url, { params })
.pipe(map((res: JSON) => this.getObjectFromJson(res)))
.subscribe(myObject => {
this.getValueToUpdate(myObject).subscribe(newValue => {
myObject.some.value = newValue;
});
});
// return Observable<myObect>;
What is the proper sequence of rxjs operators to achieve this without these subscribes and being able to return the resulting Observable to be used later?
Solution
You are looking for switchMap:
this._http.get<JSON>(url, { params }).pipe(
map((res: JSON) => this.getObjectFromJson(res)),
switchMap(myObject => {
return this.getValueToUpdate(myObject).pipe(
// probably here you need also a catchError(err => ...),
map(newValue => {
myObject.some.value = newValue;
return myObject;
})
);
})
).subscribe(myObject => {
// here myObject is updated with newValue
});
It allows to invoke another async operation and switch (i.e. observe) on that.
The inner pipe, using the map operator, allows to combine the result of the nested async operation with the previous result.
Answered By - Alberto Chiesa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.