【问题标题】:How to dynamically query entities from an akita entity store如何从秋田实体商店动态查询实体
【发布时间】:2020-04-29 05:55:23
【问题描述】:

我有这样的实体

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$ 是可观察的。如何根据两个外部状态值选择设备?

【问题讨论】:

  • 现在可以在将forkJoin 替换为combineLastest 后工作

标签: angular typescript rxjs akita


【解决方案1】:

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

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

当你想合并两个 observable 时,可以使用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)
      })
    );

【讨论】:

  • 感谢您的回答。现在你会如何处理两个 observables? * 更新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多