首页 文章

如何在ngrx中注射初始状态

提问于
浏览
0

我正在Angular 4应用程序中实现ngrx状态管理 . 直到我尝试使用之前保存在浏览器本地存储中的状态的应用程序状态,它一直很顺利 .

我有一个关于Initial State and Ahead of Time Compilation section ngrx/store 文档的问题 . 具体来说,以下行是什么意思,我将如何设置("dynamically injecting at run-time") initialStateFromSomewhere 到从浏览器本地存储中检索的状态?

/// Pretend this is dynamically injected at runtime
const initialStateFromSomewhere = { counter: 3 };

1 回答

  • 1

    在创建减速器时,您可以为商店提供初始状态 .

    假设你有 FeatureState

    interface FeatureState {
      counter: number;
    }
    

    现在在您的reducer中,您需要创建initialState

    const initialState: FeatureState = {
      count : 0;
    }
    

    这个初始国家将在 reducer 提供给该州

    export function reducer(state: FeatureState = initialState, action: Action): State {
    

    现在,如果要动态添加 initialState ,可以从商店中检索 initialState 并将其传递给 reducer

相关问题