Search code examples
angularngrxangular-ngrx-datangrx-data

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


I'm building an Angular app for a Travel Agency. 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.

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


Solution

  • I would use the rxjs combineLatest operator for subscribing to multiple observable. Following is the illustration of your code using combineLatest operator.

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