ngrx Reducer-返回新状态的正确方法

时间:2018-09-23 14:56:55

标签: angular ngrx-store

我在Angular 5项目中使用ngrx / store。我存储的应用程序状态看起来像这样

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

我对状态对象的每个属性都有单独的化简,所以我可以分别监听每个属性的更改。然后,通过服务将该状态公开给应用程序组件。

在我的化简器(SelectedCustomerReducer)中,一项操作是用新的Customer对象替换当前选择的客户(上述第二个属性)。我对减速器应如何返回新值感到困惑。

我的减速器已经在action.payload中获得了一个新的Customer对象;所以我应该把它恢复为新状态吗?

例如

export function SelectedCustomerReducer(state: Customer = new Customer(), action: Action){
    switch(action.type){
        case 'updateSelectedCustomer':
               return action.payload; 
               //OR               
               return Object.assign({}, state, action.payload);
    }
}

1 个答案:

答案 0 :(得分:0)

First of all you have to initialize your "Reducers" into "app.module.ts".

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';

import { AppComponent } from './app.component';
import { Reducers } from './store/app.reducers';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    StoreModule.forRoot(Reducers)
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then you have to place all your "Reducers" into "ActionReducerMap". It is generic type and needless to say you must to hand interface with actions into "app.reducers.ts" file maybe. Look code below.

import { ActionReducerMap } from '@ngrx/store';

import * as shoppingList from '../shopping-list/store/shopping-list.reducers';

export interface AppState{
  shoppingList: shoppingList.State,
}

export const reducers: ActionReducerMap<AppState> = {
  shoppingList: shoppingList.shoppingListReducer
}

Then you can to create "Reducer" and to hand "State" and "Action" maybe into "shopping-list.reducers.ts" file

import * as productListActions from './shopping-list.actions';
import { Product } from '../product/product.model';

export interface State{
  products: Product[];
}

const initialState: State = {
  products: [
    new Product('PC', 5),
    new Product('OS', 10),
  ]
};

export function shoppingListReducer(state = initialState, action: productListActions.ProductListActions){
  switch(action.type){
    case productListActions.ADD:
      return {
        ...state,
        products: [...state.products, action.payload]
      };
    default:
      return state;
  }
}