在每个循环中我都有一个嵌套的订阅,其中内部订阅将外部订阅的结果作为输入。我需要代码像在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.
});
答案 0 :(得分:0)
尝试使用功能combineLatest
和higher-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中查看有关静态函数和运算符的更多信息;