我正在对我的service.ts进行请求,并将其订阅到组件中。
所有功能都按预期运行,但是这导致对网络的许多请求。我该如何更好地写这个来防止这种情况?
getDeal(id: string){
const item: AngularFirestoreCollection<Deal> = this._afs.collection(`deals`,
(ref) => ref.where(`id`, '==', id));
return item.valueChanges().pipe(
// take(1),
map(arr => {
return arr;
}),
switchMap(arr => {
const userObservables = arr.map(deal => this._afs.doc(`users/${deal.customerId}`).valueChanges()
);
return combineLatest(...userObservables)
.pipe(
map((...eusers) => {
arr.forEach((deal, index) => {
deal['customer_username'] = eusers[0][index].displayName.username;
deal['customer_avatar'] = eusers[0][index].photoURL;
});
return arr;
})
);
}),
switchMap(arr => {
const userObservables = arr.map(deal => this._afs.doc(`users/${deal.dealerId}`).valueChanges()
);
return combineLatest(...userObservables)
.pipe(
map((...eusers) => {
arr.forEach((deal, index) => {
deal['dealer_username'] = eusers[0][index].displayName.username;
deal['dealer_avatar'] = eusers[0][index].photoURL;
});
return arr;
})
);
}),
share()
);
}
在组件中,我进行订阅..
this.subDeal = this._service.getDeal(id).subscribe((deal) => {
console.log(deal) // This should log just once, but it logs multiple times
}):
如何防止多个网络请求?