NGRX Store - 创建一个模型的多个实例

时间:2017-01-18 15:26:25

标签: angular ngrx

我有ngrx /存储和运行,我正在考虑它。我可以创建一个动作和一个reducer来存储基于模型的数据,但是当我创建一个内部状态的第二个实例时,它只是在我现有的状态中添加一个新行:

Reducer.ts

import * as orderhead from '../_actions/orderhead';
import { OrderHead } from '../_models/index';
// Set State to mimic that of the OrderHead model

export interface State {
  orderID: string[];
  entryDate: string[];
  requireDate: string[];
  headerRef: string[];
  pirotity: string[];
};

// Set initial state to empty
const initialState: State = {
  orderID: [],
  entryDate: [],
  requireDate: [],
  headerRef: [],
  pirotity: [],
};


export function OHreducer(state = initialState, action: orderhead.Actions):  State{
      switch (action.type) {
        case orderhead.ActionTypes.CREATE_OH:
            // Create a new instance of the model OrderHead and store it 
            // all other aspects of the model will be updated by other actions
            const order = [...state.orderID, action.payload.orderID]
            return Object.assign({}, state,  {orderID: order})

    }
}

还有一些代码用一些数据填充商店:

createOrderHead(orderid){     
  this._store.dispatch({type: orderhead.ActionTypes.CREATE_OH, payload: {orderID: orderid} });
}

现在如果我跑:

createOrderHead('ABC123')
createOrderHead('DEF456')

我得到的是:

{  orderhead: {
    orderID: [
      'ABC123',
      'DEF456'
    ],
    entryDate: [],
    requireDate: [],
    headerRef: [],
    pirotity: []
  }
}

然而,我所追求的是:

{  orderhead: [
  {
    orderID:  'ABC123',
    entryDate: [],
    requireDate: [],
    headerRef: [],
    pirotity: []
  },
  {
    orderID:  'DEF456',
    entryDate: [],
    requireDate: [],
    headerRef: [],
    pirotity: []
  }
}]
}

我试图从提供的示例应用程序中进行一些调整,但目前我无法从中提取我需要的内容以便找到解决方案,如果有人能让我知道我的哪一部分代码需要改变才能使其工作,这将是很棒的。

我确实在减速器的开始处尝试了静止状态,但这显然只是在每次调用它时都清除它,从而破坏以前的数据。

更新工作,:

所以我更新了我的reducer,因为我建议我需要在状态内创建一个空数组,然后修改我的return语句,使用reducer:

import { OrderHead } from '../_models/index';
// Set state to  that of imported model
export interface State {
  orders : OrderHead[]
};

// Set initial state to empty
const initialState: State = {
  orders : []
};

export function OHreducer(state = initialState, action: orderhead.Actions):  State{
      switch (action.type) {
        case orderhead.ActionTypes.CREATE_OH:
            // Map payload to instance of array
            const order = [...state.orders, action.payload]
            // Assign the order to the array
            return Object.assign({}, state,  {orders: order})
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您应该将状态更改为一系列订单。然后将订单添加到数组中。

import * as orderhead from '../_actions/orderhead';
import { OrderHead } from '../_models/index';
// Set State to mimic that of the OrderHead model


export interface Order {
    orderID: string | null;
    entryDate: string | null;
    requireDate: string | null;
    headerRef: string | null;
    pirotity: string | null;
  }

export interface State {
  orders : Order[]
};

// Set initial state to empty
const initialState: State = {
  orders : []
};