Home > Net >  Run Multiple HTTP Requests One After Another and Return Observable
Run Multiple HTTP Requests One After Another and Return Observable

Time:09-05

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

CodePudding user response:

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);
    const printOrder = this.fireOrder(id);

    return newOrder.pipe(switchMap(res => printOrder(res));
  }

CodePudding user response:

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

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