-4

Consider this observable method which calls an api get bar chart data

Class:

 export interface AlarmChart {
 chartLabel: string[];
 data: number[][];
 }

Api Call

   getBarChartDataV2(period: string): Observable<AlarmChart> {

   for(let x = 0 ;x<severities.length;x++){
    //each severity all values of a week
    var countoFserverity=[];
    
        for(let i = 0 ;i<daysRangeForWeek.length;i++){

        
          let url =  `${this.config.apiCumulocityUrl}/alarm/alarms?dateFrom=${daysRangeForWeek[i].dayStart}&dateTo=${daysRangeForWeek[i].dayEnd}&severity=${severities[x]}'`;
    
         url = url.replace(/'/g,'');
         this.callApi(url).subscribe(res=>{
          let response:any = res;
            countoFserverity.push(response.alarms.length);
            //add to final when all results came

            
         });
         
        } 

   //PREVENT GOING TO THIS LINE BEFORE RESPONSE FROM API INSIDE SUBSCRIBE
    data.push(countoFserverity);
    
      }
  debugger;
  result = {
  chartLabel: labels,
  data: data,
  }; 

     return result;

 }

Api Caller

  callApi(url:string):Observable<any>{

   return   this.httpClient.get(url).pipe(
    map(res => {
     debugger;
      let response:any = res;
      return response;
      })
     );
    }
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66

1 Answers1

2

You could use rxjs zip operator, this will fire once all api calls, something similar to the following:

   const calls = [];
   for(let x = 0 ;x<severities.length;x++){
    //each severity all values of a week
    var countoFserverity=[];
    
      for(let i = 0 ;i<daysRangeForWeek.length;i++){

      
        let url =  `${this.config.apiCumulocityUrl}/alarm/alarms?dateFrom=${daysRangeForWeek[i].dayStart}&dateTo=${daysRangeForWeek[i].dayEnd}&severity=${severities[x]}'`;
  
        url = url.replace(/'/g,'');
        calls.push(this.callApi(url).pipe(
          tap((res) => {
            let response:any = res;
            countoFserverity.push(response.alarms.length);
            //add to final when all results came

            
          })));
        }
    }
         
   // this wont fire until all calls are done
   zip(...calls).subscribe((values) => {
      values.push(countoFserverity);
   }

I don't have the rest of your code so this is approximate, here is an example which works to build off of:

const calls = [];
calls.push(this.httpClient.get("https://api.giphy.com/v1/channels/search?q=house&apiKey=Gc7131jiJuvI7IdN0HZ1D7nh0ow5BU6g")
  .pipe(
    tap((val) => console.log(val))
  ));
calls.push(this.httpClient.get("https://api.giphy.com/v1/channels/search?q=house&apiKey=Gc7131jiJuvI7IdN0HZ1D7nh0ow5BU6g"));

zip(...calls).subscribe((val) => {
  console.log(val);
});
Moshezauros
  • 2,493
  • 1
  • 11
  • 15