angular - 如何将第一个可观察对象的结果用于下一个可观察对象?

标签 angular rxjs

我有这个方法:

 zip(
  this.$one.getOne(id)
     .pipe(switchMap(oneResult => {
        return this.$two.getTwo(oneResult.id)
      }))
     .pipe(switchMap(twoResult => {
        // Here I Would like to use the **oneResult** as argument to the $three observable too.
        return this.$three.getThree(oneResult.id)
     })),
   this.$four.getFour()
 ).subscribe(zipResult => {
     [getTwoResult, getThreeResult]
 }

如何将 $one Observable 结果传递给 $two Observable 和 $hree observable?我可以在第一个 switchMap 上获取它。

最佳答案

您可以在 switchMap 上使用 map 创建“resultSelector”。 switchMap有一个可用于创建相同效果的 resultSelector 函数,但在 RxJS 的 future 版本中可能会弃用它,以代替使用 map ,如下面的答案所示。您可以有效地将 oneResulttwoResult 打包到一个对象或数组中,以便在第二个 switchMap 中使用。您可以根据需要继续这样做。它看起来像这样(我添加了延迟来模拟 API 调用):

import { Component } from '@angular/core';
import { Observable, of, zip } from 'rxjs';
import { map, switchMap, delay } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  getOne(id: string): Observable<string> {
    return of('foo').pipe(delay(1000));
  }

  getTwo(id: string): Observable<string> {
    return of('bar').pipe(delay(1000));
  }

  getThree(id: string): Observable<string> {
    return of('baz').pipe(delay(1000));
  }

  getFour(id: string): Observable<string> {
    return of('foobar').pipe(delay(1000));
  }


  ngOnInit(): void {
    zip(
      this.getOne('foo').pipe(
        switchMap(oneResult =>
          this.getTwo(oneResult).pipe(
            map(twoResult => ({ oneResult, twoResult }))
          )
        ),
        switchMap(oneTwoResult => {
          console.log(oneTwoResult);
          return this.getThree(oneTwoResult.oneResult);
        })
      ),
      this.getFour('foobar')
    )
    .subscribe(result => console.log(result));
  }
}

使用switchMapresultSelector函数:

zip(
  this.getOne('foo').pipe(
    switchMap(oneResult =>
      this.getTwo(oneResult),
      (oneResult, twoResult) => ({ oneResult, twoResult })
    ),
    switchMap(oneTwoResult => {
      console.log('oneTwoResult: ', oneTwoResult);
      return this.getThree(oneTwoResult.oneResult)
    })
  ),
  this.getFour('foobar')
)
.subscribe(result => console.log(result));

这是一个StackBlitz显示此功能的实际效果。

希望对您有所帮助!

关于angular - 如何将第一个可观察对象的结果用于下一个可观察对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118806/

相关文章:

angular - 使用 Angular 以编程方式设置 Bootstrap 表单中的选择字段值

angular - 如何在 angular2-json-schema-form 中创建自定义小部件

Angular + rxjs : No provider for Subscription

javascript - 更改检测 休息调用 Angular 2

javascript - Typescript,箭头函数和 rxjs 内的 "this"问题

angular - 如何将 ngclass 绑定(bind)到一个可观察值

javascript - 如何获得绑定(bind)表达式的计数

angular - 如何最好地处理模板上同一可观察对象的多个订阅?

angular - 避免在 Angular 2+ 中嵌套订阅?

json - 错误 TS2339 : Property 'results' does not exist on type 'Response'