【问题标题】:RxJS forkJoin does not completeRxJS forkJoin 未完成
【发布时间】:2017-11-23 17:00:10
【问题描述】:

当我订阅 getAllSubModules 时,forkJoin 会执行所有这些 observables 而不会出错,但没有完成。我知道 forkJoin 仅在其所有可观察对象完成后才完成,但作为证明,我在控制台中看到 '-----' 3 次,确认一切都成功,因此所有可观察对象都已完成。

 getSubmodules(id): Observable<any> {
    return this.authService.getToken()
      .flatMap((token) => this.http.get(`${this.URL}/ROS/applications/modules/${id}/subModules?token=${token}`))
      .map((res: any) => res.data.map((subModule) => this.mapSubModules(subModule)));
  }
  getAllSubmodules(): Observable<any> {
    const tasks = [];
    this.modules.forEach((module: AppModule) => {
      const obs = this.getSubmodules(module.id).map((subModules) => {
        this.allSubModules[module.id] = subModules;
        console.log('--------------------');
      });
      tasks.push(obs);
    });
    return Observable.forkJoin(...tasks).retry(2);
  }
  mapSubModules(moduleData) {
    if (moduleData.id) {
      const subModule = <SubModule> {
        id: moduleData.id,
        parentId: moduleData.parentId,
        typeId: moduleData.typeId,
        name: moduleData.name.az,
        active: true
      };
      return subModule;
    }
  }

使用 forkJoin 时不会执行此代码:

 this.universityService.getAllSubmodules().subscribe(() => {             
        // --- Below is not executed!--
        console.log('subModules in Report Co');
        console.log(this.universityService.allSubModules);
        this.checkUrl();
        this.showChild = true;
      }, (er) => console.log(er));

但是当我使用 combineLatest 而不是 forkJoin 时,它按预期工作。 那么是什么问题呢?希望有人给点建议。

【问题讨论】:

  • 这里有很多问题:没有返回的映射调用、缺少类型、mapSubmodules 方法的模糊定义(返回类型为 void 或 SubModule)。

标签: angular rxjs rxjs5


【解决方案1】:

您的预期不正确。 console.log('--------------------') 发出 3 次仅意味着您已收到 3 个 onNext 事件。 forkJoin 等待所有 observables 完成。

如果您使用.do(next=&gt;{},err=&gt;{},complete =&gt; console.log('completed')) 查看各个流或使用.take(1) 和/或.timeout(1000) 明确定义您的流何时应该完成,请尝试一下。

authService..getToken() 发出一个值后是否完成?

【讨论】:

  • 非常感谢。添加 take(1) 解决了这个问题。这是因为 authService.getToken() 没有完成。只是接下来发出。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2019-12-14
  • 2021-03-10
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2018-10-02
相关资源
最近更新 更多