如何解决角度9:forkJoin订阅无法正常运行
我正在尝试使用可观察对象(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
中的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));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。