在组件上管理多个RxJ可观察对象

时间:2020-03-02 05:37:23

标签: angular rxjs angular6 combinelatest

下面是我的应用程序中一个组件的代码段,在我分别获取值之后,我订阅了多个可观察对象并加载数据(一个api调用)。

  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在这种情况下为我工作,但是loadData被多次调用。我相信发生这种情况是因为可观测值在更新后会发出值。服务的[studentId,teacherId,resultId,reportId,yearId]的初始值设置为0,以迎合CombineLatest。

在收到所有5个值(不是intialvalues的0)之后,有什么方法可以调用LoadData方法[api call]吗?像onComplete一样?

1 个答案:

答案 0 :(得分:4)

combineLatest补充forkJoin,将等待所有可观察物完成发射。

相关问题