简体   繁体   中英

Managing multiple RxJs Observables on a component

Below is a code snippet of a component in my application where I subscribe to multiple observables and load data [an api call] after I get values respectively.

  ngOnInit() {
    this.combinedObservable$ = combineLatest(
      this.service1.getStudentId(),
      this.service2.getTeacherId(),
      this.service3.getResultId(),
      this.service4.getReportId(),
      this.service5.getYearId(),
    ).subscribe(value => {
      this.studentId = value[0];
      this.teacherId = value[1];
      this.resultId = value[2];
      this.reportId = value[3];
      this.yearId = value[4];
      // Load Data for the page by making an api call
      this.loadData(value[0], value[1], value[2], value[3], value[4]);
    });
  }

  ngOnDestroy() {
    this.combinedObservable$.unsubscribe();
  }

CombineLatest works for me in this scenario, however the loadData is being called multiple times. I believe this is happening because of the observables emitting values after they update. The initial values for [studentId, teacherId, resultId, reportId, yearId] from the service are set to 0, to cater combineLatest.

Is there any way I can call LoadData method [api call] after all the 5 values are received [not the intialvalues of 0]? Something like onComplete?

combineLatest替换forkJoin ,这将在发出之前等待所有 observable 完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM