HTTP调用何时完成

HTTP调用何时完成

本文介绍了如何知道所有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.

当请求返回时,我将响应添加为对象数组的属性.然后,一旦我拥有所有数据,便将其绑定到组件的模板,并在此通过Pipe对其进行过滤.因此,我需要确保在所有数据完成提取之前不要绑定它.

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.allthis.buildssetupBuilds中的数据设置,但我不知道如何使用rxjs observables

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

推荐答案

Observable.forkJoinPromise.all等效,但可观察到.

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

以下是示例:

这是重构代码的方式:

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);
    });
  }
);

这样,您将确保在subscribe方法中注册的回调被调用时,所有请求都已执行.

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

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

07-28 04:05