user2004
user2004

Reputation: 1973

currentUser is null after refreshing page

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

Upvotes: 1

Views: 1196

Answers (1)

Amrit
Amrit

Reputation: 2175

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

Upvotes: 3

Related Questions