角度-如何防止相关观测值嵌套管道?

时间:2020-02-19 14:12:21

标签: angular rxjs observable

为了保持代码的整洁,我尝试防止涉及可观察对象的嵌套管道。但是,我遇到了一个星座(请参见下面的代码),在这里我无法找到一种方法。我想知道是否有办法只用一根烟斗解决这个问题?

示例代码:

class CannotSimplify {

  observableA(): Observable<number> {
    return of(1);
  }

  bDependentA(a: number): Observable<number> {
    return of(2 + a, 3 + a);
  }

  cDependentOnAAndB(a: number, b: number): Observable<number> {
    return of(a + b);
  }

  printResult(): void {
    this.observableA()
      .pipe(
        switchMap(a => this.bDependentA(a)),
        switchMap(b => this.cDependentOnAAndB(a, b)) // <-- error: a is undefined
      )
      .subscribe(c => console.log(c));
  }

}

我唯一想到的解决方案是再次管道this.bDependentOnA()。 有更好的方法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

我认为您可以为此使用zip运算符。

this.observableA()
   .pipe(
     switchMap(a => zip(of(a), this.bDependentA(a))),
     switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
   )

从RxJs 7版开始, zip运算符将被zipWith取代。 here的更多内容。

this.observableA()
   .pipe(
     switchMap(a => this.bDependentA(a).pipe(zipWith(of(a)))),
     switchMap(([b, a]) => this.cDependentOnAAndB(a, b))
   )

答案 1 :(得分:0)

我认为您想在一个管道中调用三个函数。我的解决方案是使用zip

import { Observable, of, Subscription, zip } from 'rxjs';


    printResult(): void {
        this.observableA()
        .pipe(
           switchMap(a => zip(of(a), this.bDependentA(a))),
           switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
        ).subscribe(c => console.log(c));
    }

我的示例:https://stackblitz.com/edit/angular-4ipoen

相关问题