如何处理嵌套的observable

时间:2017-01-09 21:00:03

标签: angular rxjs5

这段代码对我有用,但我想知道这是否是处理嵌套订阅的更好方法。我正在获取一个我需要循环并在另一个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
                    }
                    );
                });
            });
        });

1 个答案:

答案 0 :(得分:0)

最好不要在.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));