angular - 如何从秋田实体商店动态查询实体
问题描述
我有这样的实体
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$
它是可观察的。如何根据两个外部状态值选择设备?
解决方案
可以使用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)
})
);
推荐阅读
- javascript - Chart.js 使用数据库数组和数据结构
- javascript - 如何在按键时停止计时器?
- mongodb - 在 MongoDB 中删除有条件的项目?
- html - VS2019 WinForm 应用,带浏览器控件
- android - 如何在 Flutter 项目中使用 Android 谷歌地图
- excel - 如何为 SUMIFS 函数创建“ALL”变量
- html - Div 不在 Div 内部居中
- php - MediaWiki 1.36 内部错误:需要 intl
- html - 为什么我与引导代码一起链接的自定义 css 文件没有改变页面外观或不起作用?
- javascript - discord.js 机器人在没有声音的情况下播放音频