错误:Angular 服务中未定义 localStorage

问题描述 投票:0回答:1

我正在开发一个 Angular 应用程序,并在我的

localStorage
中遇到了
AuthService
的问题。当尝试使用
localStorage
存储用户的电子邮件以进行身份验证时,我收到错误:“localStorage 未定义”。

这是我的

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']);
    }
}

我已经导入了必要的模块,包括来自

Injectable
@angular/core
,并且我在我的服务方法中使用
localStorage

angular angularjs angular17 angular-local-storage
1个回答
0
投票

LocalStorage
仅存在于浏览器上,但是如果你有SSR,那么编写的代码也会在服务器上运行,因此访问它时,它将是未定义的,我们有一个函数可以确定它是服务器还是浏览器,我们可以应对这样的场景

//auth.service.ts

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

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

    constructor(@Inject(PLATFORM_ID) platformId: Object, private router: Router) {
        this.isBrowser = isPlatformBrowser(platformId);
        this.autoSignIn();
    }

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

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

    signOut() {
        if (this.isBrowser) {
            localStorage.removeItem('email');
        }
        this.isAuth.next(false);
        this.router.navigate(['/auth']);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.