我正在使用redux和angular,但是当我重新加载页面时,我丢失了存储,当页面重新加载时,我如何持久化这些数据?
发布于 2021-03-22 09:41:32
我知道这是一个老问题,但是因为这浪费了我很多时间,所以我把它留在这里,以防有人在找它。
存储注意事项:我在这个解决方案中使用了@angular-redux/
(来自here)
store.ts
在存储区内,创建一个函数,用于从localStorage加载state (如果存在),以及一个自定义中间件,用于在调度操作时将state保存到localStorage中
import {
IAuthInterface,
AUTH_INITIAL_STATE,
authReducer,
} from './app/reducers/authReducer';
import { combineReducers } from 'redux';
export interface IAppState {
auth: IAuthInterface;
}
export const INITIAL_STATE: IAppState = {
auth: AUTH_INITIAL_STATE
};
export const rootReducer = combineReducers({
auth: authReducer,
});
// Get Value from LocalStorage variable if it exists
export const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
// Create Middleware to Save State when an action is dispatched
export const PersistMiddleware = ({ getState }) => (next) => async (action) => {
setTimeout( () => { //used to simulate async action
const serializedState = JSON.stringify(getState());
localStorage.setItem('state', serializedState);
}, 0);
next(action);
}
const State = loadState();
export const persistedState = State ? State : INITIAL_STATE;app.module.ts
在app模块内部进行必要的导入
import {
NgRedux,
NgReduxModule,
DevToolsExtension,
} from '@angular-redux/store';
import {
IAppState,
rootReducer,
persistedState,
PersistMiddleware
} from 'src/store'; //store.ts file并将您的自定义中间件和状态传递给存储
export class AppModule {
constructor(ngRedux: NgRedux<IAppState>, devtools: DevToolsExtension) {
ngRedux.configureStore(
rootReducer,
persistedState,
[PersistMiddleware],
[devtools.enhancer()]
);
}
}使用的源:
发布于 2019-06-18 19:00:20
您可以使用此模块实现redux持久化状态https://github.com/btroncone/ngrx-store-localstorage
实现
npm install ngrx-store-localstorage --saveNGRX 4更新
将localStorageSync包装在导出的函数中。包括在StoreModule.forRoot中meta-reducers数组中。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';
import { reducers } from './reducers';
const reducers: ActionReducerMap<IState> = {todos, visibilityFilter};
export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return localStorageSync({keys: ['todos']})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];
@NgModule({
imports: [
BrowserModule,
StoreModule.forRoot(
reducers,
{metaReducers}
)
]
})
export class MyAppModule {}https://stackoverflow.com/questions/56401873
复制相似问题