Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Internal server error: localStorage is not defined - Angular 17

$
0
0

I am configuring the UserStorageService with all the necessary methods for log in and sign out of the application, but when I execute it it gives me that error

this is my code

This is the storage service

import { Injectable } from '@angular/core';const TOKEN = 'ecom-token'const USER = 'ecom-user'@Injectable({  providedIn: 'root'})export class UserStorageService {  constructor() { }  public saveToken(token: string): void{    window.localStorage.removeItem(TOKEN);    window.localStorage.setItem(TOKEN,token);  }  public saveUser(user): void{    window.localStorage.removeItem(USER);    window.localStorage.setItem(USER, JSON.stringify(user));  }  static getToken(): string{    return localStorage.getItem(TOKEN);  }  static getUser(): any{    return JSON.parse(localStorage.getItem(USER));  }  static getUserId(): string{    const user = this.getUser();    if(user == null){      return '';    }    return user.userId;  }  static getUserRole(): string{    const user = this.getUser();    if(user == null){      return '';    }    return user.role;  }  static isAdminLoggedIn(): boolean{    if(this.getToken === null){      return false;    }    const role: string = this.getUserRole();    return role == 'ADMIN';  }  static isCostumerLoggedIn(): boolean{    if(this.getToken === null){      return false;    }    const role: string = this.getUserRole();    return role == 'COSTUMER';  }  static signOut(): void{    window.localStorage.removeItem(TOKEN);    window.localStorage.removeItem(USER);  }}

this is the app component

import { Component } from '@angular/core';import { UserStorageService } from './services/storage/user-storage.service';import { Router } from '@angular/router';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrl: './app.component.scss'})export class AppComponent {  title = 'e-commerce';  isCotumerLoggedIn : boolean = UserStorageService.isCostumerLoggedIn();  isAdminLoggedIn : boolean = UserStorageService.isAdminLoggedIn();  constructor(private router: Router){}  ngOnInit(): void {    this.router.events.subscribe(event => {      this.isCotumerLoggedIn = UserStorageService.isCostumerLoggedIn();      this.isAdminLoggedIn = UserStorageService.isAdminLoggedIn();    })  }  logout(){    UserStorageService.signOut();    this.router.navigateByUrl('login')  }}

I have tried verifying the imports and so on but nothing has helped me, I re-wrote the code in case I wrote wrong but nothing is solved


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>