繁体   English   中英

使用 map 组合两个 rxjs 可观察对象的数据

[英]Combing data of two rxjs observables using map

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

// 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));

尝试在外部.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
        })
      }))))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM