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

查看:282
本文介绍了浏览器页面刷新期间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?

作为@ user184994提及的

状态仅保存在内存中.如果您希望它在页面刷新之间保持不变,请转到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时,数据一直保留到直到用户手动清除浏览器缓存,或者直到您的Web应用清除数据为止.

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/本地存储 异步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天全站免登陆