Angular 9: forkJoin đăng ký không hoạt động
Sep 06 2020
Tôi đang cố gắng tải dữ liệu trang trên một thành phần cấp cao nhất trong Angular 9 bằng cách sử dụng có thể quan sát (rxjs 6.5.1). Khi đăng ký từng dịch vụ riêng lẻ, tôi có thể thấy dữ liệu quay trở lại rất tốt:
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));
}
Khi tôi cố gắng sử dụng forkJoin, dữ liệu từ phương thức đăng ký không bao giờ được trả lại:
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)
);
}
Tôi đã thử vượt qua forkJoin một loạt các cuộc gọi dịch vụ và tôi cũng đã thử sử dụng zip, nhưng không có kết quả. Chuyện gì đang xảy ra ở đây?
Trả lời
1 OwenKelvin Sep 05 2020 at 23:18
Tôi muốn khuyên bạn nên sử dụng combineLatesttừ rxjs. Nó dễ sử dụng hơn
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));
}