角度9:forkJoin订阅无法正常运行

时间:2020-09-05 15:53:07

标签: javascript angular rxjs observable angular9

我正在尝试使用可观察对象(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,但无济于事。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

我建议使用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));
}