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

Angular17+PrimeNg主题切换时@Inject报ts(1206)错误求解决

Angular 17 + PrimeNG 17 主题切换中@Inject(DOCUMENT) 报错的解决办法

问题核心

你遇到的Decorators are not valid here.ts(1206)错误,本质是Angular 17启用的严格TypeScript装饰器检查规则,与传统构造器内@Inject装饰器的写法冲突——即便功能正常,TS仍会抛出语法校验错误。

实用解决办法

1. 改用Angular 16+推荐的inject()函数写法(优先推荐)

放弃构造器内的@Inject装饰器,改用类内注入的方式,完全符合Angular 17的语法规范:

import { Injectable, inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({ providedIn: 'root' })
export class ThemeService {
  // 使用inject函数注入DOCUMENT令牌
  private document = inject(DOCUMENT);

  // 主题切换逻辑示例
  switchTheme(themeName: string) {
    const themeLink = this.document.getElementById('theme-link') as HTMLLinkElement;
    themeLink.href = `${themeName}.css`;
  }
}

2. 调整TypeScript配置保留原有写法

如果坚持使用构造器内@Inject的写法,修改项目根目录的tsconfig.json:

  • 在compilerOptions中添加/修改以下配置:
    {
      "compilerOptions": {
        "experimentalDecorators": true,
        "useDefineForClassFields": false,
        // 可选:消除未初始化字段的关联警告
        "strictPropertyInitialization": false
      }
    }
    
    同时给构造器内的document字段添加非空断言:
    constructor(@Inject(DOCUMENT) private document!: Document) {}
    

3. 禁用特定TS错误(不推荐)

如果只是临时屏蔽该错误,在tsconfig.json的compilerOptions中添加:

{
  "compilerOptions": {
    "ignoreErrors": [1206]
  }
}

注意:这种方式会跳过所有TS1206错误,可能隐藏其他潜在语法问题,仅作为临时应急方案。

额外验证

确认package.json中@angular/core、@angular/common与primeng的版本均为17.x稳定版,版本不匹配可能引发不必要的类型校验异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:12:19