簡體   English   中英

結合兩個依賴的 observables (Rxjs) 的結果

[英]Combine the result of two depending observables (Rxjs)

我有兩個可觀察的 A 和 B。我首先必須得到 A,直到我可以拿 B。

如果他們是獨立的,我可以做一些類似 forkJoin 的事情來得到結果。 但由於我只有在得到 A 后才能拿 B,所以我有點掙扎。 我試過switchMap,但似乎也不起作用。

所以我想要實現的是:

  • 得到可觀察的 A
  • 得到可觀察的 B
  • 將 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);

        }

根據 ReactiveX:

zip通過指定的 function 將多個 Observable 的發射組合在一起,並根據此 function 的結果為每個組合發射單個項目

工作示例可以在 stackbitz.com 中看到。

您可以使用switchMap (resultSelector) 的第二個參數來組合結果:

public loadConfiguration(): Observable<ProductConfiguration> {
        return this.service.getA()
                   .pipe(
                       switchMap(response => this.service.getB(response.id), (a, b) => this.getData({a, b})),
                   );
    }

rxjs學習switchMap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM