[英]Wait until an unknown number of observables complete
There are quite a few questions of similar nature, I think this is a bit different. 有很多类似性质的问题,我认为这有点不同。
Consider the following code: 考虑以下代码:
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);
The issue is I do not know in advance how many times service2.getSomeItems2
will be called. 问题是我不知道预先调用
service2.getSomeItems2
多少次。
Also, zip
and forkJoin
take Observables
but I have subscribed already. 另外,
zip
和forkJoin
采用Observables
但我已经订阅了。 Maybe I can tap
instead of subscribe
'ing. 也许我可以
tap
而不是subscribe
。 But the fact remains about unknown number of Observables. 但是事实仍然是未知数的Observable。
How about this? 这个怎么样?
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))
});
There might be syntax mistakes but I think this is what you want. 可能存在语法错误,但我认为这是您想要的。 Remember you should avoid subscribe inside subscribe.
请记住,您应该避免在内部订阅。
Hope that helps! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.