【发布时间】:2020-01-29 14:03:39
【问题描述】:
在 Angular 中,我有从父组件继承的子组件。这个父组件注入了多个类。我想用我在父类中不使用的注入类来扩展子组件。在此扩展之前,不需要实例化构造函数并调用super( *args* )。但是,当我尝试扩展构造函数时,我收到以下错误消息:
派生类的构造函数必须包含“超级”调用
有没有办法在通过注入扩展类时不需要调用超类?如果这个问题有什么不清楚的地方,请告诉我。
父组件
@Component({ template: '' })
export abstract class ParentComponent<T> implements OnInit, OnDestroy {
constructor(
protected formBuilder: FormBuilder,
protected route: ActivatedRoute,
protected snackBar: MatSnackBar,
protected location: Location
) {
const routeParams = this.route.snapshot.params;
if (routeParams && routeParams.id) {
this.subjectId = this.route.snapshot.params.id;
}
}
}
子组件
export class ChildComponent extends ParentComponent<MyT> {
constructor(
/** I want to extend with the following service */
protected myService: Service
) {
// But as I instantiate this constructor, I also need to call super() with the required params
}
}
问题扩展
扩展我的问题;我不确定超类参数的双重导入并传递它是否是开销。这个问题的主要原因是因为我尽量保持代码干净,并尝试克服重复代码。为了在super调用中提供注入类而重复导入感觉有点没用。
【问题讨论】:
-
为什么调用 super 对你来说是个问题?也许有不同的解决方案可以实现您的目标。
-
我不相信有办法,您必须在子构造函数中注入所有父依赖项,并使用 super() 将它们传递给父项。
标签: angular inheritance dependency-injection abstract-class