Angular 9: a assinatura do forkJoin não está funcionando

Sep 06 2020

Estou tentando carregar dados da página em um componente de nível superior no Angular 9 usando observáveis ​​(rxjs 6.5.1). Quando eu assino cada um desses serviços individualmente, posso ver os dados retornando perfeitamente:

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 tento usar forkJoin, os dados do método subscribe nunca são retornados:

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

Eu tentei passar a forkJoin uma série de chamadas de serviço e tentei usar o zip também, sem sucesso. O que está acontecendo aqui?

Respostas

1 OwenKelvin Sep 05 2020 at 23:18

Eu recomendaria usar combineLatestde rxjs. É mais 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));
}