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

437 Views Asked by At

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

2

There are 2 best solutions below

7
On BEST ANSWER

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

you can use the zip operator to combine the observables. 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.

 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. just have refactored.