angular - 等到未知数量的 observables 完成
问题描述
有很多类似性质的问题,我认为这有点不同。
考虑以下代码:
arr = [];
this.service1.getItem()
.subscribe(item => {
Object.entries(item).forEach(([key, value]) => {
if (some_condition_true) {
this.service2.getSomeItems2(value.prop1).pipe(first())
.subscribe(result => value.xyz = result);
this.arr.push(value);
}
});
});
// This line should execute only after the 'forEach' above completes
this.someService.someMethod(arr);
service2.getSomeItems2
问题是我事先不知道会调用多少次。
还有,zip
拿forkJoin
,Observables
但我已经订阅了。也许我可以tap
代替subscribe
'ing。但事实仍然是关于未知数量的 Observables。
解决方案
这个怎么样?
this.service1.getItem()
.pipe(switchMap(items => {
const itemReqs = Object.entries(items)
.filter(v => some_condition_true_or_false)
.map(item => this.service2.getSomeItems2(item.prop1).pipe(first()));
return forkJoin(itemReqs);
}))
.subscribe(data_from_service_2_calls => {
data_from_service_2_calls.forEach(v => console.log(v))
});
可能存在语法错误,但我认为这是您想要的。请记住,您应该避免在订阅中订阅。
希望有帮助!
推荐阅读
- javascript - 网格项在列中而不是在行中 Material-UI
- python - 添加记录器导致无法腌制_thread.RLock对象错误
- java - 字段列表中的 NativeQuery 未知列
- php - 在 Azure 中将 PHP 7 与自定义 .ini 文件一起使用时出错
- python - 普通列表和 dict.items() 的区别
- twitter-bootstrap - Bootstrap 4中的弹出底部导航栏
- javascript - 在 vue.js 项目中风格化谷歌地图
- java - 零坐标的Libgdx 3d问题
- c++ - 如何检查是否在编译时调用了模板化方法?
- ruby-on-rails - 避免 Heroku 清理一些资产