【问题标题】:Combing data of two rxjs observables using map使用 map 组合两个 rxjs observables 的数据
【发布时间】:2021-08-08 07:36:55
【问题描述】:

我有两个服务调用两个独立的外部 API(productDataService、productPrice),它们返回 observables。然后我有一个名为 productService 的第三个服务,它最终需要向我的控制器返回一个 observable,这是从两个外部服务调用函数的结果。正如您将在下面看到的那样,我从一项服务(外部可观察)获取产品列表,然后需要依次调用另一个服务功能(内部可观察)来获取该产品的价格。

// Both services functions are using HttpService and returning observables.
getProductInfo() {
    return this.productDataService.getProducts()
        .pipe(map((prod: any) => this.productPriceService.getProductPriceById(prod.id)
            .pipe(map(price => {
                (
                    {
                        id: prod.created,
                        name: prod.amount,
                        price
                    }
                )
            }))))
}

以下是服务功能供参考:

// getProducts (returns an observable of an array of type product)
        return this.httpService.get(url, config).pipe(map(res => res.data.list.map(item => {
            return {
                id: item.id,
                name: item.name
            }
        })));

// getProductPriceById (returns an Observable of type number)
return this.httpService.get(url, config).pipe(map(res => res.data.price));

【问题讨论】:

  • 当从外部 observable 转到内部 observable 时,需要使用 switchMap 或 mergeMap 来代替 map。

标签: javascript angular rxjs nestjs


【解决方案1】:

尝试在外部 .pipe 调用中使用 switchMap 运算符而不是 map 运算符。

getProductInfo() {
  return this.productDataService.getProducts()
    .pipe(switchMap((prod: any) => this.productPriceService.getProductPriceById(prod.id)
      .pipe(map(price => {
        ({
          id: prod.created,
          name: prod.amount,
          price
        })
      }))))
}

【讨论】:

  • 谢谢!这会返回一个数组还是一个 Observable?我希望它遵循 Angular 应用程序从服务到组件的正常异步流程,或者像 NestJS 应用程序从服务到控制器一样作为被订阅的 Observable。
  • 理想情况下,您应该在 getProducts 方法本身中执行此操作,并且您的组件不应进行第二次 API 调用以获取产品价格。取决于相当多的用例。如果您想一次只获取一种产品的价格,然后将其附加到特定索引处的数据中,您可以单独调用getProductPriceById,然后将其添加到产品中特定索引处的产品中数组。
猜你喜欢
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多