angular - 此构造函数与 Angular 依赖注入不兼容,因为它在参数列表索引 0 处的依赖无效
问题描述
在我的 Angular 9 应用程序中,我有一个抽象类:
export abstract class MyAbstractComponent {
constructor(
protected readonly cd: ChangeDetectorRef,
) {
super();
}
// ...
}
和一个扩展它的组件:
@Component({
// ...
})
export class MyConcreteComponent extends MyAbstractComponent {
// ...
}
一切正常,除了测试,我得到以下错误:
错误:此构造函数与 Angular 依赖注入不兼容,因为它在参数列表索引 0 处的依赖无效。如果依赖类型是像字符串这样的原始类型,或者如果此类的祖先缺少 Angular 装饰器,则可能会发生这种情况。
请检查 1) 索引 0 处的参数类型是否正确,以及 2) 为此类及其祖先定义了正确的 Angular 装饰器。
解决方案
我们在迁移到版本 9 时遇到了同样的问题。最后我们发现我们忘记为一些抽象组件添加装饰器。从 v9 开始,所有使用 Angular DI 的类都必须具有 Angular 类级别的装饰器。
常春藤兼容性示例中的示例:
前:
export class DataService {
constructor(@Inject('CONFIG') public config: DataConfig) {}
}
@Injectable()
export class AppService extends DataService {...}
后:
@Injectable() // <--- THIS
export class DataService {
constructor(@Inject('CONFIG') public config: DataConfig) {}
}
@Injectable()
export class AppService extends DataService {...}