首页 > 解决方案 > 如何从秋田实体商店动态查询实体

问题描述

我有这样的实体

interface IDevice {
  id: string;
  name: string;
  brand: string;
  plan: 'contract' | 'unlocked';
}

和实体店

interface DevicesState extends EntityState<IDevice> {
  selectedBrand: string | undefined;
  selectedPlan: 'contract' | 'unlocked';
}

我想根据所选品牌查询和过滤实体。

我唯一的尝试是这个

  selectedBrand$ = this.select('selectedBrand');
  selectedPlan$ = this.select('selectedPlan');
  devices$ = this.selectedBrand$ 
    ? this.selectAll({
        filterBy: [
         entity => entity.brand === this.selectedBrand$,
         entity => entity.plan === this.selectedPlan$,
        ]
      })
    : this.selectMany([]);

这是行不通的,因为this.selectedBrand$它是可观察的。如何根据两个外部状态值选择设备?

标签: angulartypescriptrxjsakita

解决方案


可以使用switchMap先观察选中的品牌,然后根据选中的品牌切换到店铺选择:

selectedBrand$ = this.select('selectedBrand');
devices$ = this.selectedBrand$
  .pipe(
      switchMap(brand => brand 
          ? this.selectAll({
                filterBy: entity => entity.brand === brand
          }) 
          : this.selectMany([])
      )
  );

当你想组合两个 observables 时,你可以使用combineLatest

  devices$ = combineLatest(this.selectedBrand$, this.selectedPlan$)
    .pipe(
      switchMap(([brand, plan]) => this.selectAll({
          filterBy: [
            brand ? entity => entity.categories.map(x => x.name).includes(brand) : null,
            plan ? entity => entity.plan_tab === plan : null
          ].filter(x => x !== null)
      })
    );

推荐阅读