Could I store object with its methods in @ngrx

Itz*_*tch 6 ngrx angular ngrx-entity

I wanted to store objects with their methods with @ngrx/entity . Can it cause any problems in application? (Angular 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

There is the class with method 'complete' mission. I want to save it by @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 }) {}
}
Run Code Online (Sandbox Code Playgroud)

There is the action to add Mission object with its method to @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;
  }

}
Run Code Online (Sandbox Code Playgroud)

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

tim*_*ver 5

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

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