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

Angular 18项目localStorage未定义及DOM属性错误排查求助

Angular 18项目两类错误的问题分析与解决

一、localStorage未定义错误

错误信息

ERROR ReferenceError: localStorage is not defined
    at _CartService.getCartFormLocalStorage (/Users/jan/Projekts/PflanzenApp/src/app/services/cart.service.ts:64:21)
    at _CartService (/Users/jan/Projekts/PflanzenApp/src/app/services/cart.service.ts:12:28)
    at Object.CartService_Factory (/Users/jan/Projekts/PflanzenApp/src/app/services/cart.service.ts:66:3)
    at eval (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:3233:47)
    at runInInjectorProfilerContext (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:871:9)
    at R3Injector.hydrate (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:3232:21)
    at R3Injector.get (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:3095:33)
    at ChainedInjector.get (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:16599:36)
    at lookupTokenUsingModuleInjector (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:5746:39)
    at getOrCreateInjectable (/Users/jan/Projekts/PflanzenApp/node_modules/@angular/core/fesm2022/core.mjs:5794:12)

问题原因

Angular 18默认启用SSR(服务端渲染),服务初始化时可能运行在非浏览器环境(如Node.js),此时localStorage这个浏览器专属API不存在。你的CartService在类属性初始化阶段直接调用了依赖localStorage的getCartFormLocalStorage()方法,导致服务端初始化时抛出错误。

适配解决方案

  1. 引入Angular的PLATFORM_ID和isPlatformBrowser工具,用于判断当前运行环境是否为浏览器
  2. 将cart的初始化逻辑移到构造函数中,仅在浏览器环境下读取localStorage

修改后的CartService代码:

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Cart } from '../classes/cart';
import { Observable, BehaviorSubject } from 'rxjs';
import { Plant } from '../classes/plants';
import { CartItem } from '../classes/cart-item';

@Injectable({
  providedIn: 'root'
})
export class CartService {
  private cart: Cart;
  private cartSubject: BehaviorSubject<Cart>;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    // 仅在浏览器环境下读取localStorage
    if (isPlatformBrowser(this.platformId)) {
      this.cart = this.getCartFormLocalStorage();
    } else {
      this.cart = new Cart();
    }
    this.cartSubject = new BehaviorSubject(this.cart);
  }

  addToCart(plant: Plant): void {
    let cartItem = this.cart.items.find(item => item.plant.id === plant.id);
    
    if (cartItem) 
        return;

    this.cart.items.push(new CartItem(plant));
    this.setCartToLocalStorage();
  }

  removeFromCart(plantId: string): void {
    const plantIdNumber = Number(plantId);
    this.cart.items = this.cart.items.filter(item => item.plant.id !== plantIdNumber);
    this.setCartToLocalStorage();
  }

  changeQuantity(plantId: string, quantity: number): void {
    const plantIdNumber = Number(plantId);
    let cartItem = this.cart.items.find(item => item.plant.id === plantIdNumber);

    if (!cartItem) 
      return;

    cartItem.quantity = quantity;
    cartItem.price = quantity * cartItem.plant.price;
    this.setCartToLocalStorage();
  }

  clearCart(){
    this.cart = new Cart();
    this.setCartToLocalStorage();
  }

  getCartObservable(): Observable<Cart>{
    return this.cartSubject.asObservable();
  }

  private setCartToLocalStorage(): void {
    // 仅在浏览器环境下操作localStorage
    if (!isPlatformBrowser(this.platformId)) return;
    
    this.cart.totalPrice = this.cart.items.reduce((prevSum, currenItem) => prevSum + currenItem.price, 0);
    this.cart.totalCount = this.cart.items.reduce((prevSum, currenItem) => prevSum + currenItem.quantity, 0);
    const cartJson = JSON.stringify(this.cart);
    localStorage.setItem('Cart', cartJson);
    this.cartSubject.next(this.cart);
  }

  private getCartFormLocalStorage(): Cart {
    const cartJson = localStorage.getItem('Cart');
    return cartJson ? JSON.parse(cartJson) : new Cart(); 
  }
}

二、无效属性名错误

错误信息

core.mjs:6619 ERROR DOMException: Failed to execute 'setAttribute' on 'Element': ']' is not a valid attribute name.
    at EmulatedEncapsulationDomRenderer2.setAttribute (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-3JBJB2WG.js?v=e3cfc332:2873:10)
    at setUpAttributes (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:2703:18)
    at setupStaticAttributes (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:7957:5)
    at Module.ɵɵelementStart (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:15639:3)
    at ShoppingCartTitleComponent_Template (http://localhost:4200/main.js:843:9)
    at executeTemplate (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:8146:5)
    at renderView (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:8932:7)
    at renderComponent (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:8914:3)
    at renderChildComponents (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:8961:5)
    at renderView (http://localhost:4200/@fs/Users/jan/Projekts/PflanzenApp/.angular/cache/18.0.2/vite/deps/chunk-5K2TKP3A.js?v=e3cfc332:8946:7)

问题原因

错误指向ShoppingCartTitleComponent的模板,说明该组件的HTML中存在语法错误:某个属性名包含了无效字符],比如属性绑定语法写错(例如[ngClass}]、[someProp=value]这类错误写法),或者直接将]作为属性名使用。

解决方案

检查ShoppingCartTitleComponent的HTML模板文件,重点排查:

  • 所有属性绑定([property])和事件绑定((event))的语法是否正确,确保括号配对、没有多余符号
  • 静态属性名是否合法,避免使用]这类特殊字符
  • 插值表达式({{}})的语法是否正确,没有语法错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 10:43:09