这段代码对我有用,但我想知道这是否是处理嵌套订阅的更好方法。我正在获取一个我需要循环并在另一个http调用中使用的数组。这样有效吗?
this.storeService.fetchStores(this.currentCoordinates).subscribe(nearestStores => {
nearestStores.forEach(store => {
this.stockService.fetchStockResults(ean, store.id).subscribe(stock => {
this.stockResults.push({
storeObject: store,
ean: stock.ean,
ranged: stock.ranged,
inStock: stock.quantity > 0 ? true : false
}
);
});
});
});
最好不要在.subscribe()
其中也可能出错的情况下执行异步操作。您最好将这些调用嵌入到Rx流中,以便进行错误处理和并发控制之类的操作:
this.storeService.fetchStores(this.currentCoordinates)
.mergeMap(_ => _) /* emit all values from the stores array as separate values in the rx stream */
.mergeMap(
store => this.stockService.fetchStockResults(store.ean, store.id))
.catch(err => Rx.Observable.of({ ean: -1, range: false, quantity: -1})),
(store, stock) => ({
storeObject: store,
ean: stock.ean,
ranged: stock.ranged,
inStock: stock.quantity > 0 ? true : false
}),
10 /* concurrency; how many in-flight requests do you want?*/
)
.toArray()
.subscribe(stockResults => console.log(stockResults));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句