如何知道所有 Angular2 HTTP 调用何时完成 [英] How to know when all Angular2 HTTP calls are finished

查看:18
本文介绍了如何知道所有 Angular2 HTTP 调用何时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,它将监控我们跨不同服务器的所有应用程序的当前版本号.这是通过向每个应用程序中的 txt 文件发出 http 请求来完成的.我正在使用 foreach 循环来做到这一点.

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.

我遇到的问题是我不确定如何(使用 Observables)知道所有请求何时完成.

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 将响应添加到我的应用程序数组中.

setupBuilds adds the response to my array of applications.

我正在寻找的东西实际上是一个 Promise.all 我将在其中绑定this.buildssetupBuilds 中的数据设置,但我不知道如何使用 rxjs observables

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

推荐答案

Observable.forkJoinPromise.all 等价,但用于 observables.

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

这是一个示例:

以下是重构代码的方法:

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

这篇关于如何知道所有 Angular2 HTTP 调用何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆