首页 > 解决方案 > 从 Observable 链返回所有结果

问题描述

在我的 Angular 应用程序中,我试图实现以下目标

  1. 执行ObservableA
  2. 当 A 完成时Observable,使用 A 的结果执行 B
  3. 当 B 完成时,返回A 和 B的结果

如果没有第三点,我想这会很简单,我会做这样的事情:

this.myService.getData()
  .pipe(
    flatMap(firstResult => this.myService.getMoreData(firstResult.someField))
  ).subscribe(secondResult => {
      // process the data
  });

问题是这种方式我最终只能访问secondResult,但我也需要firstResult

我不是 RxJS observables 方面的专家,所以我真的很感激任何关于如何解决这个问题的建议。

标签: javascriptrxjs

解决方案


您可以将第二个结果映射到两个结果的数组。

this.myService.getData()
  .pipe(
    concatMap(firstResult => this.myService.getMoreData(firstResult.someField).pipe(
      map(secondResult => [firstResult, secondResult]),
    ))
  ).subscribe(([first, second]) => ...);

推荐阅读