角2.如何检查 observable 是否已完成? [英] Angular2. How can I check if an observable is completed?

查看:27
本文介绍了角2.如何检查 observable 是否已完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的页面中有一个生成报告的按钮.该报告需要在页面加载时使用 http 调用加载到其余端点的数据,但我不能保证在用户按下报告按钮时加载它们.

In my page there is a button that generates a report. That report needs data that is loaded using a http call to a rest endpoint when the page is loaded, but I do not have a guarantee that they are loaded when the user presses the report button.

我如何观察 observable 以查看它是否已完成,如果未完成,则等待操作直到 http 调用完成?部分代码如下:

How can I watch the observable to see if it is completed, and if incomplete, to wait on the action until the http call is completed? Here is some of the code:

loadCompanies(): void {
    this._companyService.getCompanies().subscribe(
        response => {
            this.companiesModel = response;
        },
        err => console.log(err)
    );
}

generateReport() {
   // check if observable that loads companies is completed and do the 
   // action using companiesModel.
} 

一个选项是在加载公司中设置一个带有'loading'和'completed'值的标志,并在generateReport()中等待直到标志完成,但如果可能的话,我更喜欢使用 Observable API 的解决方案.

One option is a flag set in loading companies with values of 'loading' and 'completed', and make a wait in generateReport() until the flag is completed, but I would prefer a solution using the Observable API if possible.

推荐答案

您可以使用 subscription 中的 onCompleted 回调来实现.例如,假设您在用户按下报告按钮时显示加载栏;

You can do this by using onCompleted callback in subscription. For example, let's say you show loading bar when user press report button;

loadCompanies(): void {
     this._companyService.getCompanies().subscribe(
          response => {
               this.companiesModel = response;
          },
          err => {
               console.log(err);
               //closeLoadingBar();
          },
          () => {
               //do whatever you want
               //closeLoadingBar()
          }
     )
}

generateReport() {
    //showLoadingBar()
    this.loadCompanies();
}

如果你的 http 调用出错,onCompleted 方法不会被调用,只会调用 onError 方法.如果成功,onCompleted 方法将在您的 onNext 方法之后调用.

If you get error from your http call, onCompleted method will not be invoked, only onError will be invoked. If it is successful, onCompleted method will be called after your onNext method.

这是订阅的文档.希望能帮到你!

这篇关于角2.如何检查 observable 是否已完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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