Angular 17组件继承报错求助:构造函数调用问题
问题分析与解决方案
你的问题出在子组件构造函数没有正确传递父组件所需的依赖,同时违反了TypeScript派生类构造函数的执行规则:
错误原因拆解
- 第一个错误
Cannot find name 'httpService':子组件构造函数里的httpService既不是局部变量,也没有作为参数注入,TypeScript无法识别这个标识符。 - 第二个错误
'super' must be called before accessing 'this':TypeScript明确规定,派生类构造函数必须先调用super(),之后才能使用this,因此你不能在super()中传递this.httpService。
修正后的代码
子组件需要先在自身构造函数中注入myCustomHttpService,再将这个注入的实例传递给父类的super():
export class ParentComponent { constructor(public httpService: myCustomHttpService) {} } export class ChildComponent extends ParentComponent { // 先注入父类依赖,再传递给super constructor(private httpService: myCustomHttpService) { super(httpService); } }
额外说明
如果子组件本身不需要直接使用httpService,可以省略访问修饰符(private/public),直接将注入的实例作为参数传递:
export class ChildComponent extends ParentComponent { constructor(httpService: myCustomHttpService) { super(httpService); } }
只要myCustomHttpService已经在对应模块中声明为可注入服务,Angular的依赖注入系统会自动解析并提供实例。
内容的提问来源于stack exchange,提问作者Yogesh
相关产品推荐
相关产品推荐

