Run Multiple HTTP Requests One After Another and Return Observable

933 views Asked by At

I have two observable request functions below and although it works, I need the fire print to run after the newOrder api and return the observable. I tried using mergeMap but it just skipped through without providing any error.

postNewOrder(id: string, item: Item) {
  this.cloverMerchantIdAndTokenSet();
    
  const body = {
    'order_id': id,
    'item': Item
  };
    
  const newOrder = this.http.post<Order>(`${environment.apiUrl}/orders/createOrder`, body);
  const printOrder = this.fireOrder(id);
    
  return forkJoin(newOrder, printOrder);
}
    
fireOrder(id: string) {
  this.cloverMerchantIdAndTokenSet();
  const body = {
    'order_id': id
  };
  return this.http.post<any>(`${environment.apiUrl}/Orders/print`, body);
}

for mergeMap, the code is all the same just instead of returning the fork of the 2 requests, I did:

return newLineItem.pipe(
  mergeMap(Response => printOrder)
);
2

There are 2 answers

5
Naren Murali On

I think you are looking for switchMap

postNewOrder(id: string, item: Item) {
   this.cloverMerchantIdAndTokenSet();

    const body = {
      'order_id': id,
      'item': Item
    };

    const newOrder = this.http.post<Order>(`${environment.apiUrl}/orders/createOrder`, body);

    return newOrder.pipe(switchMap(res => this.fireOrder(res.id));
  }
0
Salketer On

The problem is that you are returning the function instead of calling it and returning the result.

return newLineItem.pipe(
      mergeMap(Response => printOrder())
    );