Angular 9: forkJoin subscribe non funziona

Sep 06 2020

Sto cercando di caricare i dati della pagina su un componente di primo livello in Angular 9 utilizzando osservabili (rxjs 6.5.1). Quando mi iscrivo a ciascuno di questi servizi individualmente, posso vedere i dati che tornano correttamente:

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

Quando provo a utilizzare forkJoin, i dati dal metodo di sottoscrizione non vengono mai restituiti:

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

Ho provato a passare forkJoin una serie di chiamate di servizio e ho provato a utilizzare anche zip, senza alcun risultato. Cosa sta succedendo qui?

Risposte

1 OwenKelvin Sep 05 2020 at 23:18

Consiglierei di utilizzare combineLatestda rxjs. È più facile da usare

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