0

I have two service calls. One which returns a list of products and the other one which returns a list of inventory for those products.

My requirement is to merge these two calls so that I can display them in a table. That is a product along with its current inventory.

I am really lost as to how I can combine these two separate service calls. Both have sku has common column name.

service call 1 product

  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]);
      });
  }

service call 2, both have sku in common

  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 Answers 2

1

You can use the forkJoin of RXJS to call multiple service all together, see the bellow code:

 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
});

You need to import import { forkJoin } from 'rxjs';

Sign up to request clarification or add additional context in comments.

Comments

1

ForkJoin comes to rescue here.

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);

Then use forkJoin,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.