Angular 9:forkJoin 订阅不起作用

EJ *_*gan 4 javascript observable rxjs angular angular9

我正在尝试使用 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));
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用 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)
  );
}
Run Code Online (Sandbox Code Playgroud)

我尝试过传递 forkJoin 一系列服务调用,也尝试过使用 zip,但无济于事。这里发生了什么事?

Owe*_*vin 5

我建议使用combineLatestfrom 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));
}
Run Code Online (Sandbox Code Playgroud)

  • 这有效!仍在深入研究文档以了解 forkJoin 出了什么问题...... (3认同)