合并两个相关可观察变量(Rxjs)的结果

时间:2020-05-15 12:32:10

标签: angular rxjs

我有两个观测值A和B。 在获得B之前,我首先必须获得A。

如果他们是独立的,我可以做类似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
      );
    }
    

目前我有点迷路了。 问候 奥利弗

3 个答案:

答案 0 :(得分:0)

您可以这样做:

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
      );
    }),
  );
}

答案 1 :(得分:0)

尝试使用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);

        }

According to ReactiveX:

zip通过 指定的功能并根据以下内容为每个组合发出单个项目 该功能的结果

Work example can be seen at stackbitz.com.

答案 2 :(得分:0)

您可以使用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 learn switchMap