Angular 5 Ngrx State lost during browser page refresh

穿精又带淫゛_ 提交于 2019-11-28 09:38:28

问题


I am new to angular 5 and Ngrx, some how i managed to implement a login functionality, once login is success i am taking the user to dashboard. But if I refresh the page the user state seems to be lost. How to make the user state persistent even the page reloads ?


回答1:


How to make the user state persistent even the page reloads?

as @user184994 Mentioned NGRX state is only held in memory. If you want it to persist between page refreshes Go for LocalStorage or sessionStorage

localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data.

I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular

For Angular 5:

npm install @ngx-pwa/local-storage@5

Register it in your RootModule

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

Inject and use it

import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

Usage

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});



回答2:


local-storage and sessions-storage introduce security risks (user info can be manipulated) and I think there is a better answer to how to address the underlying issue of how to survive a browser refresh.

In general, you're probably better off putting some code into the app component's onInit method to reload data that needs to survive a browser refresh.



来源:https://stackoverflow.com/questions/50428320/angular-5-ngrx-state-lost-during-browser-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!