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

后端 未结 6 549
轮回少年
轮回少年 2020-12-09 08:39

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

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 09:29

    The solution I came up with is to use a shared observable, save the request as a hot observable that way when the report button is clicked it will wait for the request or immediately generate if the request is complete.

    public companiesModel: Company[];
    
    /** pending request, hot Observable (will emit immediately if complete) */
    private companiesRequest: Observable;
    
    constructor(
      private _companyService: CompanyService
    ) {}
    
    public ngOnInit(): void {
      this.loadCompanies();
    }
    
    public generateReport(): void {
      if (this.companiesRequest) {
        // will not make an other network request
        this.companiesRequest.subscribe(
          response => {
            // action using companiesModel.
          },
          err => console.log(err)
        );
      }
    }
    
    private loadCompanies(): void {
      this.companiesRequest = this._companyService.getCompanies().pipe(shareReplay());
      this.companiesRequest.subscribe(
        response => {
          this.companiesModel = response;
        },
        err => console.log(err)
      );
    }
    

    https://stackblitz.com/edit/check-if-an-observable-is-completed?file=src%2Fapp%2Fapp.component.ts

    Update: You could take it one step further and make the UI async https://stackblitz.com/edit/check-if-an-observable-is-completed-async-ui?file=src%2Fapp%2Fapp.component.html

提交回复
热议问题