结合两个角度服务呼叫-角度

时间:2019-05-23 19:07:34

标签: javascript angular typescript

我有两个服务电话。一个返回产品列表,另一个返回这些产品的库存列表。

我的要求是合并这两个调用,以便可以在表中显示它们。那是一种产品及其当前库存。

我真的迷失了如何组合这两个单独的服务电话。两者都有sku具有共同的列名。

服务电话1产品

  getProducts() {
    this.http
      .get<{ message: string; products: any }>(
        'http://localhost:3000/api/products'
      )
      .pipe(
        map(productData => {
          return productData.products.map(product => {
            return {
              sku: product.sku,
              style_code: product.style_code,
              id: product._id
            };
          });
        })
      )
      .subscribe(transformedProducts => {
        this.products = transformedProducts;
        this.productsUpdated.next([...this.products]);
      });
  }

服务呼叫2,都共有sku

  getInventory() {
    this.http
      .get<{ message: string; inventory: any }>(
        'http://localhost:3000/api/inventory'
      )
      .subscribe(inventoryData => {
        this.inventory = inventoryData.inventory;
        this.inventoryUpdated.next([...this.inventory]);
      });
  }

2 个答案:

答案 0 :(得分:1)

您可以使用RXJS的forkJoin一起调用多个服务,请参见以下代码:

 forkJoin(
     this.http.get('http://localhost:3000/api/products'),
     this.http.get(`http://localhost:3000/api/inventory?prodId=${this.proId}`)
 ).subscribe( data => {             
        const [products, inventory] = data; 
},err => {          
    // show errors
});

您需要导入import { forkJoin } from 'rxjs';

答案 1 :(得分:1)

ForkJoin来这里营救。

const productService = this.http.get<{ message: string; products: any }>('http://localhost:3000/api/products').pipe(//your piping);
const inventorySerivce = this.http.get<{ message: string; inventory: any }>('http://localhost:3000/api/inventory').pipe(//your piping);

然后使用forkJoin

forkJoin([productService,inventoryService]).subscribe([productData,inventoryData] => {  
  this.products = productData;
  this.productsUpdated.next([...this.products]);
  this.inventory = inventoryData.inventory;
  this.inventoryUpdated.next([...this.inventory]);
});