switchMap 与 forkJoin 不显示结果

Anu*_*mar 2 rxjs angular

我的用例是:我必须通过对MeasurementUnit每个ProductCategory进行 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
  );
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ado 5

forkJoin仅当所有源可观察对象完成时才会发出。

您可以使用combineLatest它,一旦所有源可观察对象至少发出一次,它就会发出。


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

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 }))
  );
}
Run Code Online (Sandbox Code Playgroud)