angular - 带有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
);
}
解决方案
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 }))
);
}
推荐阅读
- linux - 重启linux后MongoDB服务终止
- qt - QML SplitView - 手动调整孩子的大小
- android - 来自哪个活动的广播接收器的上下文信息?
- java - 无需加载即可播放视频
- windows - Winsock - 重传序列递增
- excel-formula - 用于两个标准的适当公式
- ruby-on-rails - Wasabi::Resolver::HTTPError: Error: 500 for url
- java - HarmonyOS 在 Android OS 中 valueAnimator.removeAllUpdateListeners() 的替代方法是什么?
- java - 如何使用多个用户对 Elasticsearch 进行身份验证
- c# - UWP - 如何在项目属性更改时更改 ItemsControl 项目的 DataTemplate?