我可以将对象及其方法存储在@ngrx中

时间:2018-12-04 13:05:49

标签: angular ngrx ngrx-entity

我想使用@ ngrx / entity将对象及其方法存储起来。会在应用程序中引起任何问题吗? (角度2-7)

mission.class.ts:

import { v4 as uuid} from 'uuid';

export class Mission {

  id: string;
  title: string;
  completed: boolean;

  constructor (missionTitle: string, completed?: boolean) {
    this.id = uuid();
    this.title = missionTitle;
    this.completed = completed;
  }

  complete() {
    this.completed = true;
  }
}

有一个带有“完成”任务方法的类。我想通过@ ngrx / entity保存它。

missions.actions.ts:

export enum MissionActionTypes {
  AddMission = '[Mission] Add Mission'      
}

export class AddMission implements Action {
  readonly type = MissionActionTypes.AddMission;

  constructor (public payload: { mission: Mission }) {}
}

有一项操作可以将Mission对象及其方法添加到@ ngrx / store

missions.reducer.ts:

export interface MissionsState extends EntityState <Mission> {

}

export const adapter: EntityAdapter <Mission> = createEntityAdapter<Mission>();

export const initialState: MissionsState = adapter.getInitialState();

export function reducer(state = initialState, actions: MissionActions) {

  switch (actions.type) {
  
    case MissionActionTypes.AddMission:
      return adapter.addOne(actions.payload.mission, state);
      
    default: 
      return state;
  }

}

当我使用select()从商店中获取Mission对象时,可以调用它的“ complete”方法。但是我不确定这种方法将来是否会在应用程序中引起任何问题。

1 个答案:

答案 0 :(得分:2)

是有可能的,但这并不意味着您应该这样做。

  • 操作应可序列化(方法在序列化过程中会丢失)
  • 选择器应该是纯净的(不应引起副作用,只能从状态中读取日期)