订阅管道内的可观察对象(map())

Subscribing to an observable within a pipe(map())

我正在进行一个 http 调用,returns 可观察到产品列表。对于每个产品,我需要订阅一个包含价格的可观察对象(因为它是来自其他服务的单独请求)。

我认为这是可行的,但不确定是否应该这样做:

return this.httpService.get(url, config).pipe(map(res => res.data.map(product => {
   let price;
   this.productPriceService.getPriceByProductId(product.id).subscribe(value => price = value);
   return {
       id: product.id,
       name: product.name,
       price
   }
})));

我也尝试了以下方法,但我收到一个循环 JSON 参考错误:

return this.httpService.get(url, config).pipe(map(res => res.data.map(product => {
   return {
       id: product.id,
       name: product.name,
       price: this.productApiService.getPriceByProductId(product.id).subscribe(value => price = value)
   }
})));

您应该使用 switchMap and forkJoin 个运算符的组合。

代码应如下所示

return this.httpService.get(url, config).pipe(
  switchMap(
    res => forkJoin(
      res.data.map(product => this.productPriceService.getPriceByProductId(product.id).pipe(map(price => ({
        id: product.id,
        name: product.name,
        price
      }))))
    )
  )
);

getPriceByProductId 函数 returns 一个异步的可观察对象。所以你不能在那里使用 map 运算符。当您使用 map 运算符时,它不会等待该可观察对象完成并立即 returns 新数据。

switchMap 运算符正在创建另一个 observable 实例,以便您也可以等待它的响应。

一言以蔽之,map returns 一个值,switchMap returns 一个可观察值。