ngrx:为实体设置默认值
ngrx: set deafult value for entities
如何在 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。
我建议你为此使用默认构造函数:
export class Potato {
id: number;
weight: number;
constructor() {
weight = 0.2;
}
}
您不应该在存储中添加 类 以使其可序列化,好吧,您的马铃薯是,但很容易在其中添加函数,因为它存在,然后就不再存在了。
我会改用工厂函数来创建 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}));
如何在 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。
我建议你为此使用默认构造函数:
export class Potato {
id: number;
weight: number;
constructor() {
weight = 0.2;
}
}
您不应该在存储中添加 类 以使其可序列化,好吧,您的马铃薯是,但很容易在其中添加函数,因为它存在,然后就不再存在了。
我会改用工厂函数来创建 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}));