[英]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.