首页 > 解决方案 > 带有forkJoin的switchMap不显示结果

问题描述

我的用例是:我必须通过MeasurementUnit对 eachProductCategory进行 api 调用来获取每个ProductCategory.

这是我的一项服务的片段。在findAll组件中订阅时,它永远不会收到值。然而,一些值被记录为标记。我究竟做错了什么?

是否有其他方法可以获得相同的结果?

findAll(): Observable<ProductCategory[]> {
  return this.http.get<UnresolvedProductCategory[]>(`product-categories/`).pipe(
    tap(categories => console.log(categories)),  // is logged
    switchMap(categories => forkJoin(categories.map(this.resolveCategory.bind(this)))),
    tap(categories => console.log({ finalCategories: categories })) // is not logged
  );
}

resolveCategory(category: UnresolvedProductCategory): Observable<ProductCategory> {
  return this.measurementUnits.findOne(category.measurementUnit).pipe(
    map(measurementUnit => ({ ...category, measurementUnit })),
    tap(category => console.log({ category })) // is logged for each category
  );
}

标签: angularrxjs

解决方案


forkJoin只有在所有源 observables 都完成后才会发出。

您可以combineLatest改用它,一旦所有源 observables 至少发出一次,它就会发出。


或者,您可以使用take(1)来确保所有源 observables 在第一次发射后完成:

findAll(): Observable<ProductCategory[]> {
  return this.http.get<UnresolvedProductCategory[]>(`product-categories/`).pipe(
    tap(categories => console.log(categories)),
    switchMap(categories => forkJoin(categories.map(
      this.resolveCategory.bind(this).pipe(take(1))
    ))),
    tap(categories => console.log({ finalCategories: categories }))
  );
}

推荐阅读