我无法弄清楚如何用另一个 Observable 的结果更新一个 Observable 的结果:
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>;
rxjs 运算符的正确顺序是什么,可以在没有这些 subscribe
的情况下实现此目的,并且能够返回结果 Observable 以供以后使用?
最佳答案
您正在寻找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
});
它允许调用另一个异步操作并对其进行切换(即观察)。
内部管道
使用map
运算符,允许将嵌套异步操作的结果与先前的结果组合起来。
关于angular - 如何使用不同 Observable 的值更新 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77439997/