问题描述
我正在为旅行社构建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运算符组合可观察值。还有一些其他功能,如最新,合并等。请阅读官方文档,并确定要自己使用哪个文档。
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.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)
}
});
});