How to find out when all Angular2 HTTP calls are completed

I am writing an application that will track the current build number of all our applications on different servers. This is done by requesting the http to txt file in each application. I do this using a foreach loop.

The problem I am facing is that I do not know how (using Observables) to know when all requests are completed.

When requests are returned, I add the response as a property of an array of objects. Then, when I have all the data, I bind it to the component template, where it is filtered through Pipe. Thus, I need to make sure that I do not bind it until all the data is complete.

This is how I get 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 a response to my array of applications.

What I'm looking for is Promise.all , where I will this.builds to setting the data in setupBuilds , but I don’t know how to do it using observable rxjs

+6
source share
1 answer

Observable.forkJoin is the equivalent of Promise.all , but for observables.

Here is an example:

Here's how you can 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 completed when the callback registered in the subscription method is called ...

+14
source

All Articles