Angular服务中出现localStorage is not defined错误求助
解决Angular AuthService中“localStorage is not defined”错误
这个错误的核心原因是你的AuthService作为根注入服务,其constructor会在应用初始化时立即执行(包括服务器端渲染场景,比如Angular Universal),而服务器端环境中不存在localStorage对象,直接访问就会抛出未定义的错误。
解决方案:区分浏览器/服务器环境后再操作localStorage
Angular提供了PLATFORM_ID令牌和isPlatformBrowser工具函数,可以帮你判断当前代码是否运行在浏览器环境中。修改你的AuthService如下:
// auth.service.ts import { Injectable, Inject, PLATFORM_ID } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs'; import { isPlatformBrowser } from '@angular/common'; @Injectable({ providedIn: 'root', }) export class AuthService { public isAuth = new BehaviorSubject<boolean>(false); constructor( private router: Router, @Inject(PLATFORM_ID) private platformId: Object // 注入PLATFORM_ID ) { this.autoSignIn(); } autoSignIn() { // 先判断是否在浏览器环境 if (isPlatformBrowser(this.platformId)) { if (localStorage.getItem('email')) { this.isAuth.next(true); this.router.navigate(['/dashboard']); } } } signIn(email: string) { if (isPlatformBrowser(this.platformId)) { localStorage.setItem('email', email); this.isAuth.next(true); this.router.navigate(['/dashboard']); } } signOut() { if (isPlatformBrowser(this.platformId)) { localStorage.removeItem('email'); this.isAuth.next(false); this.router.navigate(['/auth']); } } }
关键说明
- 注入
PLATFORM_ID:这是Angular提供的内置令牌,用于标识当前运行的平台(浏览器/服务器)。 isPlatformBrowser:该函数接收PLATFORM_ID,返回布尔值,判断是否处于浏览器环境。只有返回true时,才执行localStorage相关操作,避免在服务器端触发错误。- 如果你的应用没有使用SSR,也建议保留这个判断——它能避免应用在非浏览器环境下初始化时出现意外错误,提升代码健壮性。
内容的提问来源于stack exchange,提问作者Anand
相关产品推荐
相关产品推荐

