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

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


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!


One more solution:

Actually subscribe function takes three parameters:

onNext onError onCompleted

this._companyService.getCompanies().subscribe(    (response) => { this.companiesModel = response; },    (err) => { console.log(err) },    (finally) => { console.log('finally') });


Method

finally()

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/finally.md