浏览器刷新后Ngrx Store重置,如何使应用程序保持状态?

INF*_*SYS 11 redux ngrx angular ngrx-store

我从一个组件发出一个动作

this.store.dispatch({type : STORE_TEAMCREST , payload : team.crestURI});
Run Code Online (Sandbox Code Playgroud)

在另一个组件中,我从商店中选择使用

this.store.select(state => state.table.teamCrest).subscribe(data => this.teamCrest = data);
Run Code Online (Sandbox Code Playgroud)

如果我的应用程序按顺序向后或向前进行,这样可以正常工作,但是一旦我执行浏览器刷新状态,就会失去它的值,如何保留它的值,以便它可以在浏览器刷新时运行.

hai*_*mot 18

您的商店有一个subscribe函数,只要调度操作就会调用该函数,并且状态树的某些部分可能已更改.对于一个简单的解决方案,您可以将状态保存到本地存储:

this.store.subscribe(function() {
    localStorage.setItem('state', JSON.stringify(this.store.getState()));
})
Run Code Online (Sandbox Code Playgroud)

文档在这里

请注意,您需要将状态字符串化以将其存储在本地存储中

要使用此状态,您需要将本地存储状态localStorage.getItem('state')(如果存在)作为reducer中的默认状态.为了实现这一点,我通常有一个辅助函数检查本地存储中是否存在具有键"state"的项,如果存在则调用JSON.parse值.

默认减速机箱:

default:
        if (retrieveState()) {
            var newState = JSON.parse(retrieveState())          
            return newState
        }
        else {
            return {...whatever your default state is};
        }
Run Code Online (Sandbox Code Playgroud)

在快速浏览之后,似乎确实存在一个应该实现您想要的中间件:https://github.com/btroncone/ngrx-store-localstorage