list.map等待请求响应如何?

时间:2018-12-05 20:11:49

标签: angular typescript angular5

我有一个带有请求的地图,但是我检测到该地图不等待请求响应来获取下一个索引。

this.products = [];
productList.map((product) => {
this.productService.getProductInfo(product).subscribe(productData => {
   productData.selected = true;
   this.products.push(productData);
  });
});

地图有一种等待请求响应的方式吗?

1 个答案:

答案 0 :(得分:3)

拳头我会提出一系列请求:

const productRequests: Observable<Product>[] = productList.map(productId => this.productService.getProductInfo(productId));

然后接下来您将观察值组合在一起,您可以采用多种方式,我认为持久化顺序很重要

// loads all at once, preserves order
forkJoin(...productRequests).subscribe(productData => {
  this.products = productData;
});

// loads one by one, sort post result to preserve order
this.products = [];
merge(...productRequests).subscribe(productData => {
  this.products.push(productData);
  this.products.sort((a, b) => {
    if (a.id < b.id) {
      return -1
    }
    if (a.id > b.id) {
      return 1
    }
    return 0;
  });
});

https://stackblitz.com/edit/angular-map-request