我正在尝试以角度方式制作一个抽象组件,但出现以下错误:
Error: src/app/app.module.ts:191:5 - error TS2322: Type 'typeof AbstractFormComponent' is not assignable to type 'any[] | Type<any>'.
Type 'typeof AbstractFormComponent' is not assignable to type 'Type<any>'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
191 AbstractFormComponent
~~~~~~~~~~~~~~~~~~~~~
这是我的抽象组件:
@Component({
selector: 'app-abstract-form',
templateUrl: './abstract-form.component.html',
styleUrls: ['./abstract-form.component.scss']
})
export abstract class AbstractFormComponent implements OnInit, AfterViewInit {
protected constructor(protected formService: FormService) {
}
protected abstract getForms(): AbstractControl[];
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.getForms().forEach(f => this.formService.addForm(f));
}
}
Angular 的构造函数似乎有问题,但我需要该服务的构造函数,所以我无法删除它。 有什么方法可以将抽象类与构造函数/注入服务一起使用?
解决方案只是不将抽象组件添加到 app.modules 中。我仍然可以将它用作抽象组件,并且不会出现任何错误。
这看起来像是一个已知的打字稿问题。 https://github.com/microsoft/tsyringe/issues/20 .
您可以使用 @ts-ignore 跳过构建时类型检查。
在 Angular 14 中,为组件使用抽象类似乎可以正常工作。上面提到的错误(类型“typeof myAbstractClass”不可分配给类型“Type”)可以通过不尝试在模块中包含抽象类来纠正并将其导入该模块的子类中。只需让后代直接从abstractclass.ts 文件导入类即可。我在抽象构造函数上使用 DI。如果我需要注入抽象类中未使用的内容,我仅在子类中使用构造函数。效果很好。
像接口一样的抽象组件类只是一个样板,并且不能被实例化。所以你不能将它包含在模块声明数组中。只需将其用作接口即可。
import {SearchDataGridBaseComponent} from "@shared"; // no need decalre in the module
export class HddataComponent extends SearchDataGridBaseComponent{
.......
}