1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Error: localStorage is not defined in Angular service

Discussão em 'Angular' iniciado por Anand, Julho 4, 2025.

  1. Anand

    Anand Guest

    I'm developing an Angular application and encountering an issue with localStorage in my AuthService. When attempting to use localStorage to store the user's email for authentication purposes, I'm getting an error: "localStorage is not defined".

    Here's a simplified version of my AuthService:

    // auth.service.ts

    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { BehaviorSubject } from 'rxjs';

    @Injectable({
    providedIn: 'root',
    })
    export class AuthService {
    public isAuth = new BehaviorSubject<boolean>(false);

    constructor(private router: Router) {
    this.autoSignIn();
    }

    autoSignIn() {
    if (localStorage.getItem('email')) {
    this.isAuth.next(true);
    this.router.navigate(['/dashboard']);
    }
    }

    signIn(email: string) {
    localStorage.setItem('email', email);
    this.isAuth.next(true);
    this.router.navigate(['/dashboard']);
    }

    signOut() {
    localStorage.removeItem('email');
    this.isAuth.next(false);
    this.router.navigate(['/auth']);
    }
    }


    I've imported the necessary modules, including Injectable from @angular/core, and I'm using localStorage within my service methods.

    Continue reading...

Compartilhe esta Página