Angular 9: forkJoin subskrybuj nie działa
Sep 06 2020
Próbuję załadować dane strony na komponent najwyższego poziomu w Angular 9 przy użyciu obserwabli (rxjs 6.5.1). Kiedy subskrybuję każdą z tych usług indywidualnie, widzę, że dane wracają dobrze:
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));
}
Kiedy próbuję użyć forkJoin, dane z metody subscribe nigdy nie są zwracane:
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)
);
}
Próbowałem przekazać forkDołącz do szeregu zgłoszeń serwisowych i próbowałem również użyć zip, ale bezskutecznie. Co tu się dzieje?
Odpowiedzi
1 OwenKelvin Sep 05 2020 at 23:18
Polecam korzystanie combineLatestz rxjs. Jest łatwiejszy w użyciu
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));
}