【问题标题】:Combine the result of two depending observables (Rxjs)结合两个依赖的 observables (Rxjs) 的结果
【发布时间】:2020-05-15 21:06:16
【问题描述】:

我有两个可观察对象 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
      );
    }
    

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

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

    • 我选择了第一个建议,因为它是第一个 :-) 但还是谢谢
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      尝试使用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 将多个 Observable 的发射通过一个 指定函数并根据每个组合发出单个项目 这个函数的结果

      Work example can be seen at stackbitz.com.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-15
        • 2021-09-13
        • 2018-11-12
        • 2016-08-06
        • 1970-01-01
        相关资源
        最近更新 更多