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

如何解决Angular SSR场景下localStorage is not defined错误?

解决Angular中localStorage is not defined错误

错误原因

  • 项目启用了服务器端渲染(SSR):服务器端不存在浏览器的window对象和localStorage API,若在组件初始化阶段(比如constructor或ngOnInit钩子)直接调用localStorage,就会触发这个错误。
  • 代码在非浏览器环境执行:比如预渲染、服务端执行逻辑时,直接访问了仅浏览器才有的API。

解决方法

方案1:通过PLATFORM_ID判断浏览器环境

Angular自带PLATFORM_ID令牌,能区分当前是浏览器还是服务器环境,只有在浏览器环境下再调用localStorage。

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

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  ngOnInit(): void {
    // 先判断是否在浏览器环境
    if (isPlatformBrowser(this.platformId)) {
      this.loadUsers();
    }
  }

  loadUsers(): void {
    // 这里安全访问localStorage
    const users = localStorage.getItem('users');
    // 你的业务逻辑
  }
}

方案2:延迟到客户端渲染完成后执行

把访问localStorage的逻辑放到ngAfterViewInit钩子,这个钩子只会在客户端浏览器环境下触发,服务端不会执行它。

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements AfterViewInit {
  ngAfterViewInit(): void {
    // 此时已在客户端,可安全调用localStorage
    this.loadUsers();
  }

  loadUsers(): void {
    const users = localStorage.getItem('users');
    // 你的业务逻辑
  }
}

方案3:封装localStorage服务(推荐)

创建一个通用服务统一处理localStorage访问,自动适配SSR环境,避免每个组件重复写判断逻辑。

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

@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

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

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

  // 可以继续封装removeItem、clear等方法
}

然后在组件里注入使用:

import { Component, OnInit } from '@angular/core';
import { LocalStorageService } from '../services/local-storage.service';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  constructor(private localStorageService: LocalStorageService) {}

  ngOnInit(): void {
    const users = this.localStorageService.getItem('users');
    // 你的业务逻辑
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:27:29