EJ Morgan
EJ Morgan

Reputation: 802

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?

Upvotes: 4

Views: 3488

Answers (1)

Owen Kelvin
Owen Kelvin

Reputation: 15083

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

Upvotes: 5

Related Questions