规范ngrx数据存储中的数据形状

时间:2019-08-28 22:47:27

标签: angular typescript ngrx ngrx-store

我有一个从Firebase检索与用户关联的任务的应用程序。在下面的示例中,我检索了三个任务,但是我不明白为什么我的数据形状如下所示:

enter image description here

我希望它看起来像这样:

task: [{ ... }, { ... }, { ... }]

是否可以如上所述平整我的商店?这是我的代码如下。映射发生在TaskActions.dataReceived

import * as TaskActions from './task.actions';
import { Action, createReducer, on } from '@ngrx/store';
import { ITask } from '../../models/task';

export interface State {
  task: ITask | null;
  error: any;
}

const initialState: ITask = null;

export const taskReducer = createReducer(
  initialState,
  on(TaskActions.getData, state => ({ ...state })),
  on(TaskActions.dataReceived, (state, payload) => ({
    ...state,
    tasks: payload.payload ? [ { ...state, ...payload.payload } ] : []
  })),
  on(TaskActions.dataNotReceived, state => ({ ...state })),
  on(TaskActions.signOut, state => ({ ...state })),
  on(TaskActions.signOutSuccess, state => ({ ...state, ...initialState })),
);

export function reducer(state: ITask | undefined, action: Action) {
  return taskReducer(state, action);
}

1 个答案:

答案 0 :(得分:1)

(state, payload) => ({
    ...state,
    tasks: payload.payload ? [ { ...state, ...payload.payload } ] : []
  })

在实践中,这是将现有状态tasks对象设置为状态的副本,并将其与payload.payload对象进行合并。< / p>

您的意思是仅将有效负载添加到tasks数组中吗?如果是这样,您应该这样做

if (payload.payload) {
   return {
      ...state,
      tasks: [...state.tasks,  payload.payload]
   }
}

return state