简体   繁体   English

如何在子实体中链接父级 - ngrx、ngrx/data

[英]How to link parent in child entity - ngrx, ngrx/data

I'm building an Angular app for a Travel Agency.我正在为旅行社构建一个 Angular 应用程序。 In a hotel listing page, I need to show Country and City of the hotel.在酒店列表页面中,我需要显示酒店的国家和城市。 I'm getting Country, City and Hotel data from ngrx/data EntityService.我从 ngrx/data EntityService 获取国家、城市和酒店数据。

If I use nested subscription it work fine, but I'm sure there's a better of way of doing this.如果我使用嵌套订阅它工作正常,但我相信有更好的方法来做到这一点。

Here's my current implementation这是我目前的实现

 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), }; }); }); }); });

Could anybody sugget a better alternative for the above solution任何人都可以为上述解决方案提供更好的替代方案

you can use the zip operator to combine the observables.您可以使用 zip 运算符来组合可观察对象。 There are a few others as well liek combineLatest, merge etc. Have a read of the official documents and decide which one you want to use for yourself.还有一些其他的,例如 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: this is untested code. PS:这是未经测试的代码。 just have refactored.刚刚重构。

I would use the rxjs combineLatest operator for subscribing to multiple observable.我将使用rxjs combineLatest运算符订阅多个可观察对象。 Following is the illustration of your code using combineLatest operator.以下是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM