首页 > 解决方案 > 等到未知数量的 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问题是我事先不知道会调用多少次。

还有,zipforkJoinObservables但我已经订阅了。也许我可以tap代替subscribe'ing。但事实仍然是关于未知数量的 Observables。

标签: angularrxjs

解决方案


这个怎么样?

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))
   });

可能存在语法错误,但我认为这是您想要的。请记住,您应该避免在订阅中订阅。

希望有帮助!


推荐阅读