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

Angular依赖注入失效问题排查与求助

解决Angular依赖注入NG0202及相关装饰器/inject函数问题

1. 修正TypeScript配置(tsconfig.json)

你的module设置为commonjs,会和Angular的DI元数据处理产生冲突,尤其在配合esbuild打包时。建议修改为ES模块规范:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "ES2020", // 替换commonjs为ES2020/ESNext
    "moduleResolution": "NodeNext", // 匹配ES模块解析规则
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "baseUrl": "./"
  }
}

2. 确保esbuild正确处理装饰器元数据

在jsbundling-rails的esbuild.config.js中,显式关联你的tsconfig文件,确保TypeScript装饰器元数据被正确解析:

const path = require('path');

module.exports = {
  entry: 'app/javascript/application.js',
  output: {
    path: path.resolve(__dirname, 'app/assets/builds'),
    filename: 'application.js',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  tsconfig: './tsconfig.json', // 绑定tsconfig
  loader: { '.ts': 'ts' },
};

3. 修正@Inject装饰器的写法

出现Decorators are not valid here. ts(1206)是因为装饰器位置错误,正确的参数注入写法是将@Inject放在构造函数的参数前面:

import { Inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  // 正确写法
  constructor(@Inject(ActivatedRoute) private route: ActivatedRoute) {}
}

4. 解决inject函数找不到的问题

  • 先确认Angular版本≥14:inject是Angular 14引入的函数式DI API,低于14的版本无法使用。
  • 确保正确导入小写的inject(注意区分大写的Inject装饰器):
import { inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  private route = inject(ActivatedRoute);

  constructor() {}
}

5. 验证组件/服务的装饰器完整性

Angular的DI仅对带有合法装饰器的类生效:

  • 组件必须添加@Component装饰器
  • 服务必须添加@Injectable({ providedIn: 'root' })或在模块的providers数组中声明
    缺少这些装饰器会导致DI无法识别类的依赖,触发NG0202错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:50:25