首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在angular中使用redux持久化数据

在angular中使用redux持久化数据
EN

Stack Overflow用户
提问于 2019-06-01 05:23:38
回答 2查看 1.1K关注 0票数 1

我正在使用redux和angular,但是当我重新加载页面时,我丢失了存储,当页面重新加载时,我如何持久化这些数据?

EN

回答 2

Stack Overflow用户

发布于 2021-03-22 09:41:32

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

存储注意事项:我在这个解决方案中使用了@angular-redux/

(来自here)

store.ts

在存储区内,创建一个函数,用于从localStorage加载state (如果存在),以及一个自定义中间件,用于在调度操作时将state保存到localStorage

代码语言:javascript
运行
复制
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模块内部进行必要的导入

代码语言:javascript
运行
复制
 import {
      NgRedux,
      NgReduxModule,
      DevToolsExtension,
     } from '@angular-redux/store';
 import { 
      IAppState,
      rootReducer,
      persistedState,
      PersistMiddleware
     } from   'src/store'; //store.ts file

并将您的自定义中间件和状态传递给存储

代码语言:javascript
运行
复制
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

票数 1
EN

Stack Overflow用户

发布于 2019-06-18 19:00:20

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

实现

代码语言:javascript
运行
复制
npm install ngrx-store-localstorage --save

NGRX 4更新

将localStorageSync包装在导出的函数中。包括在StoreModule.forRoot中meta-reducers数组中。

代码语言:javascript
运行
复制
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 {}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56401873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档