Is the ngrx store persistent?

回眸只為那壹抹淺笑 提交于 2019-12-13 09:11:07

问题


Is the ngrx store persistent? In other words can we close the browser reopen it, and retrieve state that was added to the ngrx store?


回答1:


Currently ngrx/store doesn't support such functionality. But you can maintain state by using a library like ngrx-store-persist to save data to the browsers indexedDB, localStorage or WebStorage. This library automatically saves and restores ngrx/store's data. You just need to add redux keys that you want to store in the config (see "Usage" section).




回答2:


You can maintain state by using a library like idb.js to save data to the browsers indexDB, then by using the ngrx effect you can have an init effect to reload the state back when webapp loads. here is a example code let say I want to reload selected language. the effect would be:

 @Effect()
  init$: Observable<Action> = defer(() => {
    return from(storageDb.readData('app', Lang.ActionType.LANG_KEY)).pipe(
      map((data: any) => {
        const tmpData = data ? data.state : {dir: 'rtl', selected: 'ar'};
        this.translate.setDefaultLang(tmpData.selected);
        return new Lang.LanguageInit(tmpData);
      })
    );
  });

the storageDb.readData is a wrapper for idb to load data by key, the effect will kick in when effects are getting loaded it will get the data from the indexdb and if it does not find any sets default value then dispatchs an Action. ngrx best practices is to use promises in effects not in reducers since loading the data is async operation, then in your state reducer you can catch the Action like so:

case lang.ActionType.LANGUAGE_INIT: {
      return {...state, ...action.payload};
}

Using it in this way you can slice your states save them and loaded them even when lazyloading.




回答3:


The nrxg/store is in memory only. To manage state via the browser with something like pouchdb ngrx/effects can be used. More here.



来源:https://stackoverflow.com/questions/49037908/is-the-ngrx-store-persistent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!