Angular2. How to check if the observation is completed?

There is a button on my page that generates a report. This report needs data that is downloaded using an HTTP call to the resting point when the page loads, but I have no guarantee that it loads when the user clicks the report button. How can I execute a whitch observable if it is completed, and if it is not completed, in order to wait for the action until the HTTP call is completed? Here is the piece of 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 with the flag set in the company downloads with the values ​​loaded, “completed” and waiting in generateReport () until the flag is complete. But I would prefer a solution using observable api if possible.

Any tips or helpful links are welcome. Thank.

+4
4

, onCompleted subscription. , , , ;

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.

subscribe. , !

+3

concatMap, , .

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


//Create observable to generate the report
getObservableGenerateReport(response: any): Observable<myReportList> {

    return Observable.create(observer => {

      if (generateReport().isSuccessful) {
        observer.next(myReportList);
        observer.complete();
      } else {
        console.log(err, 'Ups, something was wrong!');
        observer.next({});
        observer.complete();
      }

    });
  }
+2

Another solution:

In fact, the subscription function accepts three parameters:

onNext OnError OnCompleted

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

Method

finally()

Invokes the indicated action after the observed source sequence stops gracefully or exclusively.

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

0
source

Source: https://habr.com/ru/post/1681182/


All Articles