1

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)
);
Eugene
  • 1,242
  • 1
  • 10
  • 15
z123
  • 193
  • 1
  • 15

2 Answers2

0

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));
  }
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • When I use this it works but the issue is the order created is missing notes and modifiers but if I do it with the forkjoin, it works fine. – z123 Sep 05 '22 at 07:26
  • @z123 updated my answer, maybe this might fix it – Naren Murali Sep 05 '22 at 07:30
  • Still the same issue – z123 Sep 05 '22 at 07:43
  • Hey, I believe I found the issue, if you look at my post here https://stackoverflow.com/questions/73612910/best-way-to-like-multiple-dependant-http-requests-without-multiple-subscribes, the issue is when I link then with switchmap, the updateModifications api is not called so the order is places without modifications. Is there any way I can incorporate that addModifications api so it creates the order, then adds modifications and finally prints? – z123 Sep 05 '22 at 17:37
  • @z123 the code provided is incomplete, I cant find updateModifications method, please just add another switchmap like so `newOrder.pipe(switchMap(res => this.updateModifications(res.id).pipe(switchMap(() => this.fireOrder(res.id)))))` – Naren Murali Sep 06 '22 at 12:24
0

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

return newLineItem.pipe(
      mergeMap(Response => printOrder())
    );
Salketer
  • 14,263
  • 2
  • 30
  • 58