Search code examples
angularangular-promise

Angular 4, multiple api calls and wait for results


I'm calling service api in loop and then I want to wait for the all results. I'm not sure how can I use Observable.forkJoin here.

Component:

for(let i=0;i<data.length;i++{
    this.component.getData(data[i].id).then((result: any) => {


                })
    }

Service:

getData(parameters:any): Promise<Object> {
    return this.query(parameters)
  }

Solution

  • The key here is Promise.all, which waits for all promises to resolve before executing your callback.

    let promises = data.map(d => this.component.getData(d.id));
    
    Promise.all(promises).then(results => {
      console.log(results);
    });