[英]Angular RXJS, how do I get all data in subscribe after using multiple mergeMap calls (sequentially)?
I'd like to get all data similar to how 'forkJoin' does it after making multiple HTTP calls sequentially using MergeMap.在使用 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?
)
If no observable's parameter depend on the previous call如果没有 observable 的参数依赖于之前的调用
you can use concat
, which will play the observables is a sequence, each time waiting on the previous to finish (unlike merge
)您可以使用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));
If each call depends on the previous one there is no "clean" way to do it, you have to pass the data youself.如果每个调用都依赖于前一个调用,则没有“干净”的方法,您必须自己传递数据。
One way to achieve this is use forkJoin
and the spread operator实现此目的的一种方法是使用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.