Angular 9: forkJoin subscribe ne fonctionne pas

Sep 06 2020

J'essaie de charger des données de page sur un composant de niveau supérieur dans Angular 9 à l'aide d'observables (rxjs 6.5.1). Lorsque je m'abonne à chacun de ces services individuellement, je peux voir les données revenir très bien:

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

Lorsque j'essaye d'utiliser forkJoin, les données de la méthode subscribe ne sont jamais retournées:

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

J'ai essayé de passer forkJoin à un éventail d'appels de service et j'ai également essayé d'utiliser zip, en vain. Qu'est-ce qu'il se passe ici?

Réponses

1 OwenKelvin Sep 05 2020 at 23:18

Je recommanderais d'utiliser combineLatestde rxjs. C'est plus facile à utiliser

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