Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - Angular2. How can I check if an observable is completed?

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.

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...