在第二个 observable 中修改第一个 observable 的结果并返回更新的结果

问题描述

我有一个方法 exampleMethod() 返回 2 个连续服务调用的结果(getData1()getData2()),而 getData2() 必须修改 {{1} 返回的数据}} 在 getData1() 返回之前。目前,嵌套服务调用在我们已经从 exampleMethod() 返回之后执行,但为时已晚。我知道在另一个 observable 中调用订阅是一种不好的做法,并且可能会导致问题,所以我在问什么是正确的方法来做到这一点。下面的示例代码。谢谢!

exampleMethod()

解决方法

您说内部订阅不优雅是对的。您需要 RxJS switchMap 运算符和 forkJoin 函数来处理多个同时请求。

试试下面的方法

exampleMethod(): Observable<any> {   // <-- define return type here
  return this.myService.getData1().pipe(
    map(res => ({...res,res.orders: someValue})),switchMap(res =>
      forkJoin(
        res.orders.map(order =>
          this.myService.getData2().pipe(map((orders: any[]) =>       // <-- pip the `map` operator here
            ({...res,res.status: orders.find(o => o.number === order.number).status})
          ))
        )
      )
    )
  );
}

编辑:为 RxJS pipe 包含 map

,

您可以使用高阶 Observable 来实现。我怀疑 switchMap 可能不是您要找的,而是 concatMapconcatAll

return this.myService.getData1().pipe(
    map((res) => {
      res.orders = ["someValue"];
      return res;
    }),map((res) => 
      // <-- use switch map to internally subscribe to inner observable
      res.orders.forEach((order: any) => 
        this.myService.getData2().pipe(
          first(),tap(/* do something */)
        );
      )
    ),concatAll(),// <-- concat all inner-observables values in order
    last() // ensure that only the last value is emitted to outer observable
  );

不过要记住一件事,observable 不会同步发出值。因此 exampleMethod() 将始终在 observable 处理任何值之前返回。一种方法,虽然我不推荐它,但在异步方法中等待 observable 的完成:

async function exampleMethod(){
    return await this.dataService.getData()
       .pipe(/* whatever*/ )
       .toPromise(); // this will resolve when the observable is complete
}