![](/img/trans.png)
[英]Angular & RxJS - Combining Multiple XHR Service calls using .mergeMap
[英]Angular RXJS, how do I get all data in subscribe after using multiple mergeMap calls (sequentially)?
在使用 MergeMap 按順序進行多個 HTTP 調用后,我想獲取類似於“forkJoin”的所有數據。
this.dataService.getData1().pipe(
mergeMap(response1 => this.dataService.getData2()),
mergeMap(response2 => this.dataService.getData3()),
mergeMap(response3 => this.dataService.getData4()),
).subscribe(
//How do I get response1, response2, response3 and response4 here?
)
如果沒有 observable 的參數依賴於之前的調用
您可以使用concat
,它將播放可觀察對象是一個序列,每次都等待前一個完成(不像merge
)
var arr = [
this.dataService.getData1(),
this.dataPublicationsService.getData2(),
this.dataPublicationsService.getData3(),
this.dataPublicationsService.getData4(),
];
concat(...arr).pipe(toArray()).subscribe((a) => console.log(a));
如果每個調用都依賴於前一個調用,則沒有“干凈”的方法,您必須自己傳遞數據。
實現此目的的一種方法是使用forkJoin
和傳播運算符
class Foo {
dataService: { getData1: () => Observable<number> };
dataPublicationsService: {
getData2: () => Observable<string>;
getData3: () => Observable<number>;
getData4: () => Observable<object>;
};
bar() {
this.dataService
.getData1()
.pipe(
mergeMap((response1) =>
forkJoin([of(response1), this.dataPublicationsService.getData2()])
),
mergeMap((rest) => // rest is [number, string]
forkJoin([of([...rest]), this.dataPublicationsService.getData3()])
),
mergeMap((rest) => rest is [number, string, number]
forkJoin([of(...rest), this.dataPublicationsService.getData4()])
)
)
.subscribe((rest) => {
// [number, string, number, object]
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.