如何在子实体中链接父级-ngrx,ngrx /数据

问题描述

我正在为旅行社构建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)
        }
    });
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...