angular - ngrx 存储减速器配置(角度 5)
问题描述
我在我的 Angular 5 项目中使用 ngrx/store。我存储的应用程序状态有多个属性(切片)。我希望能够单独收听任何这些属性的更改。所以在这种情况下,我应该使用多个减速器 - 每个状态切片一个吗?可以用一个减速机来实现吗?我猜这是做不到的,因为使用一个 reducer,我们将返回整个状态的一个新副本,而不是一个切片。例如
class AppState{
private customerList: Customer [];
private selectedCustomer: Customer;
private countriesOperational: Country [];
}
我希望能够仅在 selectedCustomer 上收听更改,所以我可以这样做:
store.select(state => state.selectedCustomer).subscribe((data) => {
})
解决方案
首先 - 没有必要有几个减速器。一旦你觉得你当前的 reducer 太大/有多个职责/由于某些约束应该拆分,就应该实施新的 reducer。
回到您的问题 - 假设您的客户拥有“id”属性。在我想要展示的场景中,该应用程序将显示当前 ID 列表 - 来自 customerList。customerList 将使用 ngrx 操作动态更新(模板将监听更改)。
在组件中:
public customerIds$: Observable<string[]>;
public ngOnInit(): void {
this customerIds$ = this.store.select(
state => state.customersList.map(customer => customer.id);
);
}
在您的模板中:
<div *ngFor="let id of customerIds$ | async">
{{id}}
</div>
现在(使用异步管道)您将 html 模板与 ts 组件连接起来。因此,假设您有一个按钮将新客户添加到customersList:
<button (click)="addNewCustomer()">Add new customer</button>
该addNewCustomer()
方法正在调度一个操作,该操作由您的商店处理。一个动作的结果隐藏在减速器中,就像这样:
... (reducer logic)
case ADD_NEW_CUSTOMER:
return {
...state,
customersList: [...state.customersLits, action.payload]
在哪里:
action.payload - 是您要添加的新客户
[...state.customersList ...... ] 语法 - 需要使用不可变方法更新数组 - 更多信息可以在这里找到:https ://vincent.billey.me/pure-javascript-immutable-array/
单击按钮后,模板中将显示新的客户 ID
推荐阅读
- sql-server - sqlpackage 发布操作停留在初始化部署状态
- neo4j - 查找按时间顺序排列的网络事件的最后一页
- ios - 使用滚动视图或集合视图构建 iOS 日历,如日视图
- c++ - 在 Visual Studio Code 中设置 OpenGL 项目
- vue.js - 如何在 Quasar Vue V2 框架中设置一些全局函数/mixin
- java - 无法将“spring.freemarker”下的属性绑定到 ...FreeMarkerTemplateAvailabilityProvider
- javascript - 我可以认为 JavaScript 的 WeakMap 中的值是弱可达的吗?
- ios - 选择下拉菜单在 Safari 浏览器中的 iPhone iOS 版本 14.6 上不起作用
- jquery - 在使用 jQuery 在 django 中制作自动完成搜索功能时,我犯了哪些错误?
- angular - 计算属性名称必须是“字符串”、“数字”、“符号”或“任意”类型