Observables与在for循环中生成的combineLatest Observable组合



我正在尝试组合可观测值,其中每个可观测值都在for循环中获得输入。我的问题是,如果没有for loop,我会知道如何执行,如果我知道for loop将提前循环的数组->我会把所有东西都放在combineLatest中。

如果我不知道sections的大小,有人知道我会怎么做吗?

非常感谢!

getArticleSectionsContent(pageId: string): Observable<any> {
return this.getArticleSections(pageId).pipe(
switchMap(sections => {
return combineLatest([
this.getArticleSectionContent(pageId, sections[0].index),
this.getArticleSectionContent(pageId, sections[1].index),
this.getArticleSectionContent(pageId, sections[2].index),
]).pipe(
map(([a, b, c]) => {
return { a, b, c };
})
);
})
);
}

如果您不知道部分的大小,请使用map操作符循环遍历您的数组,将其转换为可观测值数组,如下所示:

getArticleSectionsContent(pageId: string): Observable<any> {
return this.getArticleSections(pageId).pipe(
switchMap(sections => {
const articleSectionContentObsArray = sections.map(section => {
return this.getArticleSectionContent(pageId, section.index);
});
return combineLatest(articleSectionContentObsArray);
})
);
}

最新更新