currentUser is null after refreshing page

寵の児 提交于 2020-01-24 23:57:26

问题


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.

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

How to solve this?

app.component.ts

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

login.service.ts

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

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

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

回答1:


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.

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



来源:https://stackoverflow.com/questions/58952995/currentuser-is-null-after-refreshing-page

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