Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9: forkJoin subscribe not working

I'm trying to load page data on a top level component in Angular 9 using observables (rxjs 6.5.1). When I subscribe to each of these services individually, I can see the data coming back just fine:

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

When I try to use forkJoin, the data from the subscribe method is never returned:

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

I've tried passing forkJoin an array of service calls and I've tried using zip as well, to no avail. What's happening here?

like image 356
EJ Morgan Avatar asked Oct 19 '25 21:10

EJ Morgan


1 Answers

I would recommend using combineLatest from rxjs. Its easier to use

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));
}
like image 162
Owen Kelvin Avatar answered Oct 21 '25 10:10

Owen Kelvin