Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when all Angular2 HTTP calls are finished

Tags:

angular

rxjs

I'm writing an application that will monitor the current build number of all of our applications across different servers. This is done by making an http request to a txt file in every application. I'm doing that using a foreach loop.

The issue I'm having is that I'm not sure how (using Observables) to know when all of the requests are finished.

As the requests come back, I add the response as a property of an array of objects. Then once I have all of the data, I bind it to the component's template, where it gets filtered by a Pipe. As such, I need to make sure I don't bind it until all of the data is finished coming down.

Here is how I'm getting the data:

this.apps.forEach(app => {
  app.Environments.forEach(env => {
    this._buildMonitorService.getBuilds(env.URL)
      .subscribe((data) => {     
        setupBuilds(this.apps,data.url,data._body);
      });                
  });
});

setupBuilds adds the response to my array of applications.

The thing I'm looking for is effectively a Promise.all where I'll bind this.builds to the data setup in setupBuilds but I don't know how to do that with rxjs observables

like image 664
Alex Kibler Avatar asked Mar 15 '16 14:03

Alex Kibler


1 Answers

Observable.forkJoin is the equivalent to Promise.all but for observables.

Here is a sample:

  • Angular2 Observable.forkJoin of observable variables - ReferenceError: Observable is not defined

Here is the way you could refactor your code:

var observables = [];
this.apps.forEach(app => {
  app.Environments.forEach(env => {
    observables.push(this._buildMonitorService.getBuilds(env.URL));
  });
});

Observable.forkJoin(observables).subscribe(
  (result) => {
    result.forEach((data) => {
      setupBuilds(this.apps,data.url,data._body);
    });
  }
);

This way you will be sure that all requests were executed when the callback registered in the subscribe method is called...

like image 60
Thierry Templier Avatar answered Dec 02 '22 21:12

Thierry Templier