此构造函数与 Angular Dependency Injection 不兼容,因为它在参数列表索引 0 处的依赖项无效

Fra*_*rzi 14 typescript angular angular-test angular-ivy angular-dependency-injection

在我的 Angular 9 应用程序中,我有一个抽象类:

export abstract class MyAbstractComponent {
  constructor(
    protected readonly cd: ChangeDetectorRef,
  ) {
    super();
  }

  // ...
}
Run Code Online (Sandbox Code Playgroud)

和一个扩展它的组件:

@Component({
  // ...
})
export class MyConcreteComponent extends MyAbstractComponent {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

一切正常,除了测试,我收到以下错误:

错误:此构造函数与 Angular 依赖注入不兼容,因为它在参数列表索引 0 处的依赖项无效。如果依赖类型是像字符串这样的原始类型,或者此类的祖先缺少 Angular 装饰器,就会发生这种情况。

请检查 1) 索引 0 处参数的类型是否正确,以及 2) 是否为此类及其祖先定义了正确的 Angular 装饰器。

met*_*bic 10

我们在迁移到版本 9 时遇到了同样的问题。最后我们发现我们忘记为一些抽象组件添加装饰器。从 v9 开始,所有使用 Angular DI 的类都必须有一个 Angular 类级装饰器。

来自Ivy 兼容性示例的示例

前:

export class DataService {
  constructor(@Inject('CONFIG') public config: DataConfig) {}
}

@Injectable()
export class AppService extends DataService {...}

Run Code Online (Sandbox Code Playgroud)

后:

@Injectable() // <--- THIS
export class DataService {
  constructor(@Inject('CONFIG') public config: DataConfig) {}
}

@Injectable()
export class AppService extends DataService {...}
Run Code Online (Sandbox Code Playgroud)


Eyd*_*ian 9

我花了一段时间,但是在使用 angular 10.2.3 创建新应用程序后,我的基础 tsconfig.json 没有

"emitDecoratorMetadata": true,

在编译器选项中!

再次将其添加到 后tsconfig.json,DI 按预期工作。

  • 事实上,它只能添加到 tsconfig.spec.json 中,因为它只对测试文件失败,至少在我的情况下...... (2认同)

Fra*_*rzi 7

我通过添加构造函数MyConcreteComponent并调用super(...)构造函数解决了我的问题:

@Component({
  // ...
})
export class MyConcreteComponent extends MyAbstractComponent {

  // adding this block fixed my issue
  constructor(
    protected readonly cd: ChangeDetectorRef,
  ) {
    super(cd);
  }

  // ...
}
Run Code Online (Sandbox Code Playgroud)


小智 6

在我的情况下,简单的重启 npm 修复了这个错误。


小智 5

今天,我在使用 Jest 在我的应用程序中执行测试时不得不面对这个确切的错误。运行 Angular 10.2,我有另一个规范文件,它执行完全相同的测试而没有抛出任何错误。每个类都有装饰器。我花了一个小时才找出问题:我的测试文件中有一个循环依赖项,但我没有注意到它,因为测试没有显示通常的 Angular 警告。

因此,只是为了向遇到同样问题的其他人指出,请检查您的导入!