You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17使用localStorage报错‘localStorage is not defined’求助

Angular 17 解决 localStorage is not defined 错误

核心原因

Angular 17 默认开启服务器端渲染(SSR),localStorage 是浏览器专属API,服务器端执行代码时不存在该对象,直接调用就会抛出未定义错误。你的 LocalService 直接操作 localStorage,初始化阶段代码会在服务器端执行一遍,触发报错。

修复方案

方案1:通过环境判断调用 localStorage

修改 LocalService,先确认当前处于浏览器环境再执行存储操作:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LocalService {
  name = "Das Hotel";
  
  constructor() { }

  private get isBrowser(): boolean {
    return typeof window !== 'undefined' && !!window.localStorage;
  }

  public saveData(key: string, value: string) {
    if (this.isBrowser) localStorage.setItem(key, value);
  }

  public getData(key: string) {
    return this.isBrowser ? localStorage.getItem(key) : null;
  }

  public removeData(key: string) {
    if (this.isBrowser) localStorage.removeItem(key);
  }

  public clearData() {
    if (this.isBrowser) localStorage.clear();
  }
}

方案2:使用Angular官方环境判断工具

更符合Angular规范的方式是注入 PLATFORM_ID,通过 isPlatformBrowser 方法判断环境:

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class LocalService {
  name = "Das Hotel";
  
  constructor(@Inject(PLATFORM_ID) private platformId: Object) { }

  public saveData(key: string, value: string) {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.setItem(key, value);
    }
  }

  public getData(key: string) {
    return isPlatformBrowser(this.platformId) ? localStorage.getItem(key) : null;
  }

  public removeData(key: string) {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.removeItem(key);
    }
  }

  public clearData() {
    if (isPlatformBrowser(this.platformId)) {
      localStorage.clear();
    }
  }
}

方案3:禁用SSR(仅适用于纯客户端应用)

如果不需要服务器端渲染,可直接删除项目中的SSR配置:

  1. 删除 angular.json 里的 architect > server 节点
  2. 删除项目根目录下的 main.server.ts、app.server.module.ts 等SSR相关文件

注意事项

  • 组件生命周期钩子(如 ngOnInit)在SSR模式下会在服务器端执行,调用存储方法前同样要做环境判断
  • 若需在服务器端同步数据,建议使用状态管理库(如NgRx)或服务端临时存储方案

内容的提问来源于stack exchange,提问作者CodeButcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 03:49:51