Angular 9:forkJoinサブスクライブが機能しない

Sep 06 2020

オブザーバブル(rxjs 6.5.1)を使用して、Angular9のトップレベルコンポーネントにページデータを読み込もうとしています。これらの各サービスを個別にサブスクライブすると、データが正常に返されることがわかります。

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 OwenKelvin Sep 05 2020 at 23:18

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));
}