代码之家  ›  专栏  ›  技术社区  ›  Viking22

ngrx存储减速器配置(角度5)

  •  0
  • Viking22  · 技术社区  · 6 年前

    我在Angular 5项目中使用ngrx/store。 我存储的应用程序状态有多个属性(片)。 我希望能够单独监听这些属性的变化。 所以在这种情况下,我应该使用多个减缩器——每个状态片一个减缩器吗? 一个减速器能实现吗? 我猜这是不可能的,因为使用一个reducer,我们将返回整个状态的一个新副本,而不是一个片段。 例如。

    class AppState{
        private customerList: Customer [];
        private selectedCustomer: Customer;
        private countriesOperational: Country [];
    }
    

    我希望能够仅在selectedCustomer上监听更改,因此我可以执行以下操作:

    store.select(state => state.selectedCustomer).subscribe((data) => {
    })
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Pawel Kiszka    6 年前

    首先,不需要几个减速器。如果您觉得当前的减速机太大/有多个职责/由于某些限制应拆分,则应实施新的减速机。

    回到你的问题——假设你的客户有“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组件连接起来。所以,假设您有一个按钮,可以将新客户添加到CustomerList:

    <button (click)="addNewCustomer()">Add new customer</button>
    

    还有 addNewCustomer() 方法是分派一个由您的商店处理的操作。动作的结果是隐藏在减速器中,类似于:

    ... (reducer logic)
       case ADD_NEW_CUSTOMER:
          return {
            ...state,
            customersList: [...state.customersLits, action.payload]
    

    哪里:

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