[英]Handle multiple http requests and wait for all to complete using Angular RxJs Observables
我正在使用 Observables,我有一個用例,其中:
Page[]
服務中獲取“頁面”問題是一旦所有這些請求都完成了,就必須采取一些行動。
你需要使用mergeMap和forkJoin
使用forkJoin
您可以同時觸發並行請求,它會等待所有請求完成。
this.http.get('/api/pages/')
.map((res: any) => res.json())
.mergeMap((pages: any[]) => {
if (pages.length > 0) {
return Observable.forkJoin(
pages.map((page: any) => {
return this.http.get('/api/sections/' + page_id)
.map((res: any) => {
let section: any = res.json();
// do your operation and return
return section;
});
});
);
}
return Observable.of([]);
});
}
一般來說,在嵌套異步調用時盡量保持平坦。 否則,您將創建回調地獄,這使事情比使用常規迭代代碼更加復雜:
this.http.get('/api/pages/')
.map((res: Response) => res.json())
.concatMap((pages: Page[]) => {
const observables = pages.map(p => this.http.get('whatever' + p.id));
return Observable.forkJoin(observables, (...results) =>
results.map((result, i) => {
pages[i].sections = result;
return pages[i];
})
)
})
.subscribe(pagesWithSections => ...);
forkJoin()
運算符將選擇器函數作為參數,該函數可讓您處理所有源 Observables 的結果。 我正在使用它來更新原始pages
數組並返回它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.