【问题标题】:Managing multiple RxJs Observables on a component在一个组件上管理多个 RxJs Observables
【发布时间】:2020-03-02 05:37:23
【问题描述】:

下面是我的应用程序中一个组件的代码 sn-p,我订阅了多个可观察对象并在我分别获取值后加载数据 [一个 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 个值 [不是初始值 0] 后,有什么方法可以调用 LoadData 方法 [api 调用]? onComplete 之类的?

【问题讨论】:

    标签: angular rxjs angular6 combinelatest


    【解决方案1】:

    forkJoin 替换combineLatest,这将等待所有可观察对象在发射之前完成。

    【讨论】:

    • 这是真的。但是forkJoin(this.a(), this.b(), this.c)() 现在已弃用,取而代之的是forkJoin([this.a(), this.b(), this.c()])。更棒的是,你可以forkJoin({ a: this.a(), b: this.b(), c: this.c() }).subscribe(result => console.log(result.a);)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多