使用Redux以角度持久化数据

时间:2019-05-31 21:23:38

标签: angular redux

我正在使用带有角度的redux,但是当我重新加载页面时,我失去了存储,如何在重新加载页面时保留这些数据?

2 个答案:

答案 0 :(得分:0)

您可以使用此模块实现Redux持久状态 https://github.com/btroncone/ngrx-store-localstorage

实施

npm install ngrx-store-localstorage --save

更新NGRX 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 {}

答案 1 :(得分:0)

我知道这是一个老问题,但由于这浪费了我很多时间,所以我将把它留在这里以防有人正在寻找它。

<块引用>

注意:我在这个解决方案中使用了@angular-redux/store(来自here

store.ts

在商店内部创建一个函数,从 state 加载 localStorage(如果它存在)和一个自定义中间件,每当操作发生时将 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

在应用模块内部进行必要的导入

 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()]
    );
  }
}

使用的来源:

For loadState Method

For Custom Middleware

Also For Custom Middleware