角度2.我如何检查可观察对象是否完成? [英] Angular2. How can I check if an observable is completed?

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

问题描述

在我的页面中,有一个按钮可以生成报告.该报告需要的数据是在页面加载时通过对其余端点的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.

我如何观看可观察对象以查看其是否完成,以及是否未完成,以等待操作完成,直到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.如果成功,将在您的onNext方法之后调用onCompleted方法.

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.

以下是 subscribe的文档.希望对您有所帮助!

Here is the documentation for subscribe. I hope it helps!

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

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