【问题标题】:ngrx: set deafult value for entitiesngrx:为实体设置默认值
【发布时间】:2019-01-25 18:02:58
【问题描述】:

如何在 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。

【问题讨论】:

    标签: angular typescript ngrx ngrx-entity


    【解决方案1】:

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

    export class Potato {
        id: number;
        weight: number;
    
        constructor() {
            weight = 0.2;
        }
    }
    

    【讨论】:

    • 当我想改变体重时,它会保留我的新价值吗?
    • 当然。初始权重仅在构建时设置一次。您之后输入的任何值都将保留为当前值。
    【解决方案2】:

    您不应该在存储中添加类以使其可序列化,好吧您的土豆是,但是现在它存在并且不再存在时,很容易在其中添加函数。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      相关资源
      最近更新 更多