在 NGXS 中刷新浏览器选项卡后如何保留状态?Ngrx版本的问题是在这里问的?
问问题
1949 次
2 回答
5
您可以使用存储插件保留状态:
于 2018-07-09T13:21:59.287 回答
2
修改我的整个答案。找到了更好的数据持久化方法:通过meta-reducers
坚持插件.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
}],
于 2018-07-04T13:12:23.373 回答