Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

angular - How to know when all Angular2 HTTP calls are finished

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...