From 7fa45008ee2c468b2e09a8c2f9226f1f1fc84816 Mon Sep 17 00:00:00 2001 From: Art Date: Sun, 12 Sep 2021 12:29:12 +0300 Subject: [PATCH] 104. Get user from local cache (#12) --- .../src/app/service/authentication.service.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/support-portal-frontend/src/app/service/authentication.service.ts b/support-portal-frontend/src/app/service/authentication.service.ts index 047e82e..832ef43 100644 --- a/support-portal-frontend/src/app/service/authentication.service.ts +++ b/support-portal-frontend/src/app/service/authentication.service.ts @@ -5,13 +5,14 @@ import {UserLogin} from "../dto/user-login"; import {Observable} from "rxjs"; import {User} from "../model/user"; +const USER_STORAGE_KEY = "user"; +const JWT_TOKEN_STORAGE_KEY = "jwt-token"; + @Injectable({ providedIn: 'root' }) export class AuthenticationService { - private readonly JWT_TOKEN_STORAGE_KEY = "jwt-token"; - private host: string = environment.apiUrl; private token: string | null; private loggedInUser: string | null; @@ -33,17 +34,23 @@ export class AuthenticationService { public logout(): void { this.token = null; this.loggedInUser = null; - this.storage.removeItem(this.JWT_TOKEN_STORAGE_KEY); - this.storage.removeItem("user"); + this.storage.removeItem(JWT_TOKEN_STORAGE_KEY); + this.storage.removeItem(USER_STORAGE_KEY); this.storage.removeItem("users"); } public saveToken(token: string): void { this.token = token; - this.storage.setItem(this.JWT_TOKEN_STORAGE_KEY, token); + this.storage.setItem(JWT_TOKEN_STORAGE_KEY, token); } public addUserToLocalStorage(user: User) { - this.storage.setItem("user", JSON.stringify(user)); + this.storage.setItem(USER_STORAGE_KEY, JSON.stringify(user)); } + + public getUserFromLocalStorage(): User { + let userJson = this.storage.getItem(USER_STORAGE_KEY); + return JSON.parse(userJson!); + } + }