【问题标题】:For loop should iterate only after subscribe method's body executed (nested subscribe in forloop) in angular 6只有在 Angular 6 中执行订阅方法的主体(嵌套订阅在 for 循环中)后,for 循环才应该迭代
【发布时间】:2020-07-13 01:14:42
【问题描述】:

我在每个循环中都有一个嵌套订阅,其中内部订阅将外部订阅的结果作为输入。我需要代码像在 for 循环中迭代时一样,它应该调用外部订阅并将其结果/输出传递给内部订阅。这里的 for 循环应该等到该过程完成后再进行下一次迭代。这里我提供了一个演示

this.forVar.forEach(item =>{
   this.service.outerSubscribe(item).subscribe(res=>{
      //some coding here 
      this.service.innerSubscribe(res).subscribe(res1=>{//some coding here});
   });
//for each should iterate only after both subscribes are executed.  
});

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    尝试使用函数combineLatesthigher-order mapping operator,如switchMap

    // use switchMap to get values from the inner subscription
    const createNestedSubscriptionFromItem = item => 
      this.service.outerSubscribe(item).pipe(
        switchMap(res => this.service.innerSubscribe(res))
      );
    
    // create an array of subscriptions
    const subscriptions = this.forVar.map(item => 
      createNestedSubscriptionFromItem(item)
    );
    
    // use combineLatest to get updates from all results.
    // here you can use other functions like merge or jorkJoin instead combineLatest. 
    const allResults$ = combineLatest(subscriptions);
    

    在官方API Reference中查看更多关于静态函数和运算符的信息;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      相关资源
      最近更新 更多