如何解决在第二个 observable 中修改第一个 observable 的结果并返回更新的结果
我有一个方法 exampleMethod()
返回 2 个连续服务调用的结果(getData1()
和 getData2()
),而 getData2()
必须修改 {{1} 返回的数据}} 在 getData1()
返回之前。目前,嵌套服务调用在我们已经从 exampleMethod()
返回之后执行,但为时已晚。我知道在另一个 observable 中调用订阅是一种不好的做法,并且可能会导致问题,所以我在问什么是正确的方法来做到这一点。下面的示例代码。谢谢!
exampleMethod()
解决方法
您说内部订阅不优雅是对的。您需要 RxJS switchMap
运算符和 forkJoin
函数来处理多个同时请求。
试试下面的方法
exampleMethod(): Observable<any> { // <-- define return type here
return this.myService.getData1().pipe(
map(res => ({...res,res.orders: someValue})),switchMap(res =>
forkJoin(
res.orders.map(order =>
this.myService.getData2().pipe(map((orders: any[]) => // <-- pip the `map` operator here
({...res,res.status: orders.find(o => o.number === order.number).status})
))
)
)
)
);
}
编辑:为 RxJS pipe
包含 map
您可以使用高阶 Observable 来实现。我怀疑 switchMap
可能不是您要找的,而是 concatMap 或 concatAll。
return this.myService.getData1().pipe(
map((res) => {
res.orders = ["someValue"];
return res;
}),map((res) =>
// <-- use switch map to internally subscribe to inner observable
res.orders.forEach((order: any) =>
this.myService.getData2().pipe(
first(),tap(/* do something */)
);
)
),concatAll(),// <-- concat all inner-observables values in order
last() // ensure that only the last value is emitted to outer observable
);
不过要记住一件事,observable 不会同步发出值。因此 exampleMethod()
将始终在 observable 处理任何值之前返回。一种方法,虽然我不推荐它,但在异步方法中等待 observable 的完成:
async function exampleMethod(){
return await this.dataService.getData()
.pipe(/* whatever*/ )
.toPromise(); // this will resolve when the observable is complete
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。