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

Preserve the state after broswer tab is refreshed

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

修改我的整个答案。找到了一种更好的持久化数据的方法:通过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
  }],

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

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