刷新浏览器选项卡后保留状态

时间:2018-07-04 13:12:23

标签: ngxs

在NGXS中刷新浏览器选项卡后,如何保留状态?问问题的Ngrx版本here

2 个答案:

答案 0 :(得分:2)

您可以使用存储插件来保存状态:

https://ngxs.gitbook.io/ngxs/plugins/storage

答案 1 :(得分:0)

重新回答我的全部问题。找到了一种更好的持久数据方法:通过meta-reducers

persist.plugin.ts

import {getActionTypeFromInstance} from '@ngxs/store';
import {ConstantsService} from '../constants.service';
import {tap} from 'rxjs/operators';

/*
* This plugin will
* 1. Store the state in localstorage, after every action
* 2. After page is refresed, read from localstorage data and write that into state
* */
export function persistPlugin(state, action, next) {

  console.log('entering plugin=================');
  // After every refresh first action fired will be @@INIT
  if (getActionTypeFromInstance(action) === '@@INIT') {

    // reading from local storage and writing into state, when app is refreshed
    let storedStateStr = localStorage.getItem('LOCALSTORAGE_APP_STATE');
    let storedState = JSON.parse(storedStateStr);
    state = {...state, ...storedState};
    return next(state, action);
  }

  return next(state, action).pipe(tap(result => {
  //following code will trigger after reducer
    console.log('Action happened!', result);
    localStorage.setItem('LOCALSTORAGE_APP_STATE', JSON.stringify(result));;
  }));
}

app.module.ts

  providers: [...,{
    provide: NGXS_PLUGINS,
    useValue: persistPlugin,
    multi: true
  }],