[Fixed] concat with if in angular (how to use sequential request with conditions )

Issue

I have an event which call 3 http observable. order of these request is important to me. so I have to use concat from rxjs. for example with the first request I got the data and fill my local variable values with that, then I want to check if the result of one of those local variable is true then send next request. something like that:

onMyEvent(e){
let isRoundingAdditionIsRequiered = false;
let ishavePeriodicalDiscount = false;
const api = 'api/Sales/SaleTemplate/' + e;
const firstApiGet = this.dataSourceService.generateCustomApiDataList(
      'sales',
      'SaleTemplate',
      api
    ).dataList$;
const secondApi= 'api/Sales/Addition/List?$filter=AdditionCode eq "4"'
const secondApiGet= this.dataSourceService.generateCustomApiDataList(
      'sales',
      'SaleTemplate',
      api
    ).dataList$;
const postApi =
    'api/Sales/Contract/CalculateAllRowPrices/';
    const calculatePrice=
    this.dataSourceService.generateCustomApiPost
    ('sales','Contract',postApi,this.entity).dataList$;
}

now by the result of firstApiGet I want to set isRoundingAdditionIsRequiered to true. like this:

firstApiGet.subscribe(data => { if (data.RoundingAdditionIsRequiered) {isRoundingAdditionIsRequiered =true} });

then check it for next request:

if (isRoundingAdditionIsRequiered ){
secoundApi.subscribe(data => {// codes here ...})
}
// and other codes ...

this is not work sequential so I have to use concat operator.
somthing like concat(firstApiGet,secondApiGet,postApi).subscribe(data=>{//...})
so what is the code?

Solution

You can use switchMap operator.

onMyEvent(e) {
  let isRoundingAdditionIsRequiered = false;
  let ishavePeriodicalDiscount = false;
  const api = 'api/Sales/SaleTemplate/' + e;
  const firstApiGet = this.dataSourceService.generateCustomApiDataList(
       'sales', 'SaleTemplate', api ).dataList$;
  const secondApi= 'api/Sales/Addition/List?$filter=AdditionCode eq "4"'
  const secondApiGet= this.dataSourceService.generateCustomApiDataList(
       'sales', 'SaleTemplate', api ).dataList$;
  const postApi = 'api/Sales/Contract/CalculateAllRowPrices/';
  const calculatePrice= this.dataSourceService.generateCustomApiPost(
       'sales','Contract',postApi,this.entity).dataList$;
  }
  firstApiGet.pipe(
     switchMap( data => {
        isRoundingAdditionIsRequiered = data.RoundingAdditionIsRequiered;
        return isRoundingAdditionIsRequiered ? secondApiGet : of( undefined );
     ),
     switchMap( () => calculatePrice )
  ).subscribe();
}

Leave a Reply

(*) Required, Your email will not be published