2

I am trying to build app, where i am sending one get request to get data from component. This request will be called and data will be used to execute very next step. However, it is executing next step before i get response from service.

This is my service file:

  getSabhaListDetailsName(sabhaMandalName: string): Observable<any> {
const sabhaListDetailsNameURL = this.rooturl + 'sabhatypebysabhaname';
return this.http
  .post(sabhaListDetailsNameURL,{}, { params: { sabha_name: sabhaMandalName } })
  .pipe(map(this.extractData),
   catchError(this.handleError<any>('sabhaListDetailsNameURL')));

}

this is my component file, from where i am calling service,

   this.sabhaService.getSabhaListDetailsName(element.sabha_id).subscribe(result => {
  this.tempRetrieveSabha = result.data.sabhaList;
  //return this.tempRetrieveSabha;
  //  });
  console.log(this.tempRetrieveSabha);
  this.tempRetrieveSabha.forEach(
    element1 => {
      console.log(this.tempRetrieveSabha);
      if (element1.sabha_type == element.sabha_type) {
        this.tempSabha_ID = element1.id;
        this.tempSabha_Type = element1.sabha_type;
        this.tempFollowup_ID = element.followup_id;
      }
    })
});

How can i wait for http request to finish before loop through array.

tanmay parmar
  • 279
  • 1
  • 4
  • 15

2 Answers2

0

Rxjs subscribe method will make HTTP Ajax request to trigger API call. You need to move Array loop inside subscribe method in component. Also can you please add 'extractData' code please.

Not seeing any issue in the current code.

Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
0

Try to implement async and await function or promises.

For example :

  async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url); 
  } catch(e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}

Refrence : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Ashish
  • 2,026
  • 17
  • 19