1

在ngrx实体中启动状态时如何为实体设置默认值?

马铃薯模型.ts

export class Potato {
    id: number;
    weight: number;
}

马铃薯减速器.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。

4

2 回答 2

2

我建议您为此使用默认构造函数:

export class Potato {
    id: number;
    weight: number;

    constructor() {
        weight = 0.2;
    }
}
于 2019-01-22T12:14:58.393 回答
0

你不应该在存储中添加类来保持它的可序列化,好吧你的土豆是,但是现在它存在并且它不再是它是很诱人的。

我会使用工厂函数来创建土豆。

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}));

于 2019-01-25T10:02:58.097 回答