在ngrx实体中初始化状态时,如何为实体设置默认值?
potato.model.ts
export class Potato {
id: number;
weight: number;
}
potato.reducer.ts
export interface PotatoState extends EntityState<Potato> { }
export const potatoAdapter: EntityAdapter<Potato> = createEntityAdapter<Potato>();
const potatoesInitialState: PotatoState = potatoAdapter.getInitialState();
export const initialState: State = {
potatoes: potatoesInitialState
};
export function reducer(state = initialState, action: PotatoActions): State {
switch (action.type) {
// ...
}
}
例如,我需要将默认重量设置为0.2。
答案 0 :(得分:2)
我建议您为此使用默认构造函数:
export class Potato {
id: number;
weight: number;
constructor() {
weight = 0.2;
}
}
答案 1 :(得分:0)
您不应该在存储中添加类以使其可序列化,好吧,您的土豆就是这样,但是现在它很容易在其中添加函数,而现在不再存在。
我将使用工厂函数来创建Potato。
interface Potato {
id: number;
weight: number;
}
const createPotato = (potato: Potato = { id: undefined, weight: 0.2 }) => potato;
console.log(createPotato());
console.log(createPotato({id: 20, weight: 300}));