0

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

任何人都可以为上述解决方案提出更好的替代方案吗

4

2 回答 2

1

你可以使用 zip 操作符来组合 observables。还有一些其他的,比如 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:这是未经测试的代码。刚刚重构。

于 2020-10-03T05:44:46.223 回答
1

我会使用rxjs combineLatest运算符来订阅多个 observable。以下是使用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)
        }
    });
});
于 2020-10-03T05:45:58.940 回答