繁体   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