慕蓋茨4494581
2023-02-17 11:05:16
我正在嘗試使用 observables (rxjs 6.5.1) 在 Angular 9 的頂級組件上加載頁面數(shù)據(jù)。當(dāng)我單獨(dú)訂閱這些服務(wù)中的每一項(xiàng)時,我可以看到返回的數(shù)據(jù)很好: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));}當(dāng)我嘗試使用 forkJoin 時,從未返回訂閱方法中的數(shù)據(jù):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) );}我試過傳遞 forkJoin 一系列服務(wù)調(diào)用,我也試過使用 zip,但無濟(jì)于事。這里發(fā)生了什么事?
1 回答

月關(guān)寶盒
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個贊
我建議使用combineLatestfrom 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));
}
添加回答
舉報
0/150
提交
取消