Angular 5 Ngrx 状态在浏览器页面刷新期间丢失 [英] Angular 5 Ngrx State lost during browser page refresh

查看:55
本文介绍了Angular 5 Ngrx 状态在浏览器页面刷新期间丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 5 和 Ngrx 的新手,我是如何设法实现登录功能的,一旦登录成功,我就会将用户带到仪表板.但是如果我刷新页面,用户状态似乎丢失了.即使页面重新加载,如何使用户状态持久化?

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 ?

推荐答案

如何在页面重新加载时保持用户状态?

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

as @user184994 提到的 NGRX 状态仅保存在内存中.如果您希望它在页面刷新之间保持不变,请转到 LocalStoragesessionStorage

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

localStoragesessionStorage 完成完全相同的事情并具有相同的 API,但是使用 sessionStorage 数据仅保留到窗口或选项卡已关闭,而使用 localStorage 时,数据会一直保留,直到用户手动清除浏览器缓存或您的网络应用程序清除数据为止.

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.

我建议你去@ngx-pwa/local-storage Angular 的异步本地存储

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

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

在您的 RootModule 中注册它

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

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

注入并使用

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

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

使用

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

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

这篇关于Angular 5 Ngrx 状态在浏览器页面刷新期间丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆