Angular 9: forkJoin subscribe no funciona

Sep 06 2020

Estoy tratando de cargar datos de página en un componente de nivel superior en Angular 9 usando observables (rxjs 6.5.1). Cuando me suscribo a cada uno de estos servicios individualmente, puedo ver que los datos regresan sin problemas:

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

Cuando intento usar forkJoin, los datos del método de suscripción nunca se devuelven:

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

Intenté pasar forkUnirse a una serie de llamadas de servicio y también intenté usar zip, sin éxito. ¿Que esta pasando aqui?

Respuestas

1 OwenKelvin Sep 05 2020 at 23:18

Recomendaría usar combineLatestfrom rxjs. Es más fácil de usar

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