Home » Javascript » javascript – How can I wait for each service call to my controller before running through the next one in a loop in Angular?

javascript – How can I wait for each service call to my controller before running through the next one in a loop in Angular?

Posted by: admin February 23, 2020 Leave a comment

Questions:

I have a call to a Angular service like this

this.webService.add(id)
  .subscribe(result => {
    // do some stuff
  }, error => {
    // handle error
  });

// service
add(id: number): Observable < any > {
  return this.http.post(this.baseUrl + 'webservice/add/' + id, null);
}

If I need to call this multiple times, but I want to ensure that all have completed before I show a final success/failure message, how would I do that?

Would a recursive method be appropriate or is there a more angular/javascript/callback way to do it?

ex.

for (let i = 0; i < someLength; i++) {
  this.webService.add(id)
    .subscribe(result => {
      // do some stuff
    }, error => {
      // handle error
    });
}
// now show if they all succeeded or if one failed!

My controller is asyncronous like this

[HttpPost("document/{id}")]
public async Task<IActionResult> Document(int id) {
   // do something
   var resultDto = await _webRepo.AddToWebService(info);
   return Ok(resultDto);
}
How to&Answers:

You are looking for the forkJoin operator.

This operator takes multiple observables and returns a new observable as soon as all source observables completed. You would use it like:

const serviceCalls = yourArray.map(id => this.webservice.add(id));
forkJoin(... serviceCalls)
 .subscribe((results) => results.forEach( //do something with your results ))