0

How to handle asynchronous calls in angular. I know i am getting array as undefined due to asynchronous nature but how do i solve it


private fetchData(id){
   var array = [];
   this.httpClient.get('someUrl/'+id).subscribe((organisation)=>{
      console.log(organisation.teams);   // ['team1','team2','team3']
      organisation.teams.forEach((team)=>{
          this.httpClient/get('someUrl/'+team).subscribe((teamData)=>{
             array.push(teamData);
          })
       })
       console.log(array);    // undefined
    })
}

AB B
  • 1
  • 1

1 Answers1

0

Your code seems to work fine and you are correctly using the subscribe functionality. The reason you log undefined is that the console.log(array) line is called before the get request to 'someUrl'+team has returned a value. To check this you can move the console.log(array) line inside the scope of the subscription (where the array.push(teamData) line is).

A more modern way of writing this with less indentation is to use async/await:

private async fetchData(id){
   var array = [];
   let organisation = await this.httpClient.get('someUrl/'+id).toPromise();
   console.log(organisation.teams);   // ['team1','team2','team3']
   let teamData;
   organisation.teams.forEach((team)=>{
       teamData = await this.httpClient/get('someUrl/'+team).toPromise()
       array.push(teamData);
   })
   console.log(array);
}
Erik
  • 722
  • 4
  • 11