我的 Angular 依赖项不起作用,我不知道为什么。我见过的所有资源都表明这应该有效:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor (private route: ActivatedRoute) {} // I'm the problem it's me
}
构造函数的那一行总是给我这个浏览器错误:
Error: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid.
它不是特定于ActivatedRoute的;我已经尝试过将此语法与其他依赖项一起使用,并且所有这些依赖项都发生了这种情况。
我的想法是,如果 Angular 代码是正确的,问题就在于我的代码是如何加载的。我正在使用 jsbundling-rails 和 esbuild。这是我的 tsconfig.json:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"baseUrl": "./"
}
}
如果有人知道如何解决这个问题那就太好了,但我也在尝试其他方法来解决这个问题。 我看到了另一个问题,有人在使用 Webpack 时遇到类似的错误。他说他通过“在组件构造函数中使用
@Inject
装饰器”来使其工作。我无法使用他的语法来编译它:
import { Inject } from '@angular/core';
...
export class AppComponent {
constructor(@Inject(ActivatedRoute) private route: ActivatedRoute) {}
// Decorators are not valid here. ts(1206)
另一方面,确实编译:
export class AppComponent {
private route = Inject(ActivatedRoute);
但是
this.route
的值不是一个ActivatedRoute对象,而是来自Angular装饰器代码的这个股票函数:function ParamDecorator(cls, unusedKey, index) { ... }
。我尝试了其他表达方式并得到了这些错误:
export class AppComponent {
private route = @Inject(ActivatedRoute);
// Expression expected. ts(1109)
@Injectable({ providedIn: 'root' })
export class AppComponent {
private route = inject(ActivatedRoute);
// Cannot find name 'inject'. Did you mean 'Inject'? ts(2552)
最后一个来自 Angular 文档 是正确的,但显然我正在做一些奇怪的错误。我该怎么处理这些?我想要的只是可用的依赖项;_;
错误信息
参数列表索引0处的依赖无效
表明 Angular 已经明白这个参数是它应该注入的“依赖项”,但这个特定的依赖项在某种程度上是“无效的”。
如果您在 Angular 文档中搜索错误代码 NG0201,您会发现 NG0201:找不到 {token} 的提供程序。
也就是说,这个错误消息有角度地告诉你“我找不到激活的路由?我应该从哪里得到这个?”。最可能的原因是您忘记导入
RouterModule
。
顺便说一句,将
ActivatedRoute
注入 AppComponent
中是没有意义的。它的文档say:
激活路线
提供对与插座中加载的组件关联的路由信息的访问。
由于
AppComponent
未加载到插座中,并且当 AppComponent
存在时,路线将会改变,因此 ActivatedRoute
,即使它被注入,也将是 AppComponent
首次加载时处于活动状态的路线,不是现在活动的路线。