刷新页面后,currentUser为null [英] currentUser is null after refreshing page

查看:131
本文介绍了刷新页面后,currentUser为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录组件,一个服务和一个存储助手.在刷新主页(这里需要用户数据)之前,登录方法可以正常工作,因为我正在注入空服务.因此,为解决此问题,我在app.component中创建了一个方法,该方法使用将令牌保存到localStorage的令牌来设置currentUser.

I have a login component , a service and a storage helper. The login method works fine until I refresh HomePage (here I need user's data) because I'm injecting an empty service. So, to solve this, in app.component I've created a method that sets the currentUser using the token saved it to localStorage.

我的问题是刷新页面后currentUser为null,我认为这是因为未保存令牌.

My problem is that the currentUser is null after refreshing the page and I think it is because of the token not being saved.

如何解决这个问题?

app.component.ts

app.component.ts

 getUserDetails() {
    this.accountService.getUserDetails().subscribe(res => {
      this.userService.setCurrentUser(<User>res);
    }, error => {
      StorageHelper.killSession();
    });
  }

login.service.ts

login.service.ts

  login(credentials) {
    delete credentials.rememberMe;
    return this.apiService.post(`${this.resourceUrl}/login`, credentials);
  }

login.component.ts

login.component.ts

login() {
    this.accountService.login(this.authForm.value).subscribe(res => {
      StorageHelper.saveToken((<User>res).token);
      this.userService.setCurrentUser((<User>res));
      this.router.navigateByUrl(this.getReturnUrl());
    }, error => {
    });
 }

storagehelper.ts

storagehelper.ts

private static readonly tokenKey: string = "VendorJwtToken";
private static readonly customerTypeKey: string = 'VN_CT';

public static getToken() {
    return window.localStorage[this.tokenKey];
}

public static saveToken(token: String) {
    window.localStorage[this.tokenKey] = token;
}

推荐答案

已登录的用户详细信息存储在本地存储中,因此用户如果他们刷新浏览器以及在两次刷新之间将保持登录状态浏览器会话,直到他们注销.如果您不希望用户留下在刷新或会话之间登录时,行为很容易通过将用户详细信息存储在不太持久的位置(例如,会话存储或身份验证服务的属性中.

The logged in user details are stored in local storage so the user will stay logged in if they refresh the browser and also between browser sessions until they logout. If you don't want the user to stay logged in between refreshes or sessions the behaviour could easily be changed by storing user details somewhere less persistent such as session storage or in a property of the authentication service.

您应像这样将其保存在 localStorage 中:

You should save it in localStorage like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthenticationService {
    constructor(private http: HttpClient) { }

    login(username: string, password: string) {
        return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username: username, password: password })
            .pipe(map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.token) {
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify(user));
                }

                return user;
            }));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
    }
}

您可以查看此链接以逐步进行设置:

you can have a look at this link for step by step setup : https://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial

这篇关于刷新页面后,currentUser为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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