How to know when all Angular2 HTTP calls are finis

2019-01-19 17:45发布

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

标签: angular rxjs
1条回答
贪生不怕死
2楼-- · 2019-01-19 18:15

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

Here is a sample:

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...

查看更多
登录 后发表回答