![](/img/trans.png)
[英]RxJs - Combine two observables, result selector function, zip
[英]Combine the result of two depending observables (Rxjs)
我有兩個可觀察的 A 和 B。我首先必須得到 A,直到我可以拿 B。
如果他們是獨立的,我可以做一些類似 forkJoin 的事情來得到結果。 但由於我只有在得到 A 后才能拿 B,所以我有點掙扎。 我試過switchMap,但似乎也不起作用。
所以我想要實現的是:
將 A 和 B 組合成一個結果 C
public loadConfiguration(): Observable<ProductConfiguration> { return this.service.getA().pipe( switchMap(response => { return this.service.getB(response.id); } ), map(result => this.getData(result)) // here i want A and B thogether so result should contain A and B ); }
目前我有點失落。 問候奧利弗
你可以這樣做:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return this.service.getB(response.id).pipe(
map(responseB => ({responseA: response, responseB})),
);
}),
map(result => this.getData(result)) // result already have responseA & responseB
);
}
或這個:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return this.service.getB(response.id).pipe(
map(responseB => this.getData(...)), // you have access to response and responseB here
);
}),
);
}
嘗試使用zip
方法將兩個 Observable 的兩個結果結合起來:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA().pipe(
switchMap(response => {
return Observable.zip(
this.service.getB(response.id),
of(response)
);
return this.service.getB(response.id);
})),
.subscribe(([resA, resB]) => {
console.log('resA', resA);
console.log('resB', resB);
}
zip
通過指定的 function 將多個 Observable 的發射組合在一起,並根據此 function 的結果為每個組合發射單個項目
您可以使用switchMap
(resultSelector) 的第二個參數來組合結果:
public loadConfiguration(): Observable<ProductConfiguration> {
return this.service.getA()
.pipe(
switchMap(response => this.service.getB(response.id), (a, b) => this.getData({a, b})),
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.