首页 > 解决方案 > 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) => {
})

标签: angularngrxngrx-store

解决方案


首先 - 没有必要有几个减速器。一旦你觉得你当前的 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]

在哪里:

单击按钮后,模板中将显示新的客户 ID


推荐阅读