javascript - Angular 9:forkJoin 订阅不起作用
问题描述
我正在尝试使用 observables(rxjs 6.5.1)在 Angular 9 中的顶级组件上加载页面数据。当我单独订阅这些服务时,我可以看到数据恢复得很好:
ngOnInit(): void {
const technicianSubscription = this.techniciansClientService.getByTechnicianId(this.technicianId).subscribe(technician => console.log(technician));
const technicianReviewsSubscription = this.technicianReviewsClientService.getByTechnicianId(this.technicianId).subscribe(technicianReviews => console.log(technicianReviews));
}
当我尝试使用 forkJoin 时,来自 subscribe 方法的数据永远不会返回:
ngOnInit(): void {
this.pageDataSubscription = forkJoin({
technician: this.techniciansClientService.getByTechnicianId(this.technicianId),
technicianReviews: this.technicianReviewsClientService.getByTechnicianId(this.technicianId),
}).subscribe(
// data is never logged here
data => console.log(data)
);
}
我尝试向 forkJoin 传递一系列服务调用,并且我也尝试过使用 zip,但无济于事。这里发生了什么事?
解决方案
我建议使用combineLatest
from rxjs
。它更易于使用
import {combineLatest} from `rxjs`;
componentIsActive = true;
ngOnInit(): void {
combineLatest([
this.techniciansClientService.getByTechnicianId(this.technicianId),
this.technicianReviewsClientService.getByTechnicianId(this.technicianId),
]).pipe(
map(([technician, technicianReviews]) => ({technician, technicianReviews})),
takeWhile(() => this.componentIsActive)
).subscribe(data => console.log(data));
}
推荐阅读
- google-artifact-registry - 无效的存储库类型 PYTHON。有效类型是 PYPI
- javascript - 如何让元素在滚动事件期间更改其颜色,然后恢复为原始颜色?
- java - Spring Session Redis-如何配置 RedisTempalte 以使用 jackson 序列化器/反序列化器
- mysql - 在 MySQL 中显示一个组的平均值
- twitter-bootstrap - Bootstrap:从 5 alpha 升级到最终版本 (5.1.0) 的问题
- python-3.x - 既然不推荐使用dependency_links,那么带有setuptools的额外Python包索引url?
- javascript - 尝试在本地使用 JS 跳过飞行前选项
- c - 当我在 macOS 上使用 DYLD_INSERT_LIBRARIES 启动二进制文件时,究竟会发生什么?
- vba - 插入单元格并仅向下移动单元格
- react-native - react-native useFocusEffect "holdings" 是只读错误