首页 > 解决方案 > 在页面重新加载之间保存角度应用程序的状态

问题描述

在页面重新加载之间实现状态持久性的好方法是什么?现在我不是在谈论 ngrx 上下文中的状态。我指的是当您刷新页面时,一切似乎都消失了:用户已注销,所有未保存在后端的更改都消失了,等等。

起初我认为这可以使用 localStorage 以某种方式实现,然后在我需要的每个组件中的 ngOnInit() 中初始化所有内容,但这听起来像是在发明一个轮子。我相信应该有一个现成的解决方案或某种模式。

请指教。

标签: angulartypescriptngrx

解决方案


在网络上快速搜索指向ngrx-store-localstorage,它有助于将应用程序状态存储在localstorage中。下面是他们网站的示例实现。

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 {}


推荐阅读