Angular 9: forkJoin สมัครสมาชิกไม่ทำงาน
Sep 06 2020
ฉันกำลังพยายามโหลดข้อมูลหน้าในส่วนประกอบระดับบนสุดใน Angular 9 โดยใช้ observables (rxjs 6.5.1) เมื่อฉันสมัครใช้บริการเหล่านี้ทีละรายการฉันสามารถดูข้อมูลกลับมาได้ดี:
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));
}
เมื่อฉันพยายามใช้ forkJoin ข้อมูลจากวิธีสมัครสมาชิกจะไม่ถูกส่งคืน:
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)
);
}
ฉันได้ลองส่ง fork เข้าร่วมการเรียกใช้บริการมากมายและฉันได้ลองใช้ zip ด้วย แต่ก็ไม่มีประโยชน์ เกิดอะไรขึ้นที่นี่?
คำตอบ
1 OwenKelvin Sep 05 2020 at 23:18
ฉันอยากจะแนะนำให้ใช้combineLatestจากrxjs. ใช้งานง่ายกว่า
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));
}