[英]How to link parent in child entity - ngrx, ngrx/data
我正在為旅行社構建一個 Angular 應用程序。 在酒店列表頁面中,我需要顯示酒店的國家和城市。 我從 ngrx/data EntityService 獲取國家、城市和酒店數據。
如果我使用嵌套訂閱它工作正常,但我相信有更好的方法來做到這一點。
這是我目前的實現
this.countryService.entities$.pipe(map((countries: Country[]) => countries)).subscribe((countries) => { this.countries = countries; this.cityService.entities$.pipe(map((cities) => cities)).subscribe((cities) => { this.cities = cities; this.hotelService.entities$.pipe(map((hotels) => hotels)).subscribe((hotels) => { this.hotels = hotels.map((hotel) => { return { ...hotel, country: this.countries.find((c) => c.id === hotel.countryId), city: this.cities.find((c) => c.id === hotel.cityId), }; }); }); }); });
任何人都可以為上述解決方案提供更好的替代方案
您可以使用 zip 運算符來組合可觀察對象。 還有一些其他的,例如 combineLatest、merge 等。閱讀官方文檔並決定您要自己使用哪個。
zip(this.countryService.entities$, this.cityService.entities$, this.hotelService.entities$).pipe(map(response => {
return {
countries: response[0],
cities: response[1],
hotels: response[2],
};
}).subscribe((respObj: {countries: Countries[], cities: Cities[], hotels: Hotels[]}) => {
this.countries = respObj.countries;
this.cities = respObj.cities;
this.hotels = respObj.this.hotels;
}));
PS:這是未經測試的代碼。 剛剛重構。
我將使用rxjs combineLatest運算符訂閱多個可觀察對象。 以下是使用combineLatest運算符的代碼說明。
combineLatest([
this.countryService.entities$,
this.cityService.entities$,
this.hotelService.entities$
]).subscribe(([countries, cities, hotels]) => {
this.countries = countries;
this.cities = cities;
this.hotels = hotels.map((hotel) => {
return {
...hotel,
country: this.countries.find((c) => c.id === hotel.countryId),
city: this.cities.find((c) => c.id === hotel.cityId)
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.