Angular组件基类服务注入:派生类构造函数的正确实现方式
Angular组件基类依赖注入的正确实现方式
你当前的写法存在冗余:派生类重复声明并注入myService完全没必要,override修饰符在这里也属于多余操作。以下是两种更合理的实现方案:
方案1:派生类传递依赖给基类(推荐)
基类保持原有结构(无需添加@Injectable,因为它不会被Angular直接实例化),派生类仅需在构造函数中接收依赖并传递给基类的super()调用,无需重复声明protected或override:
// 基类 export class MyComponentBase { constructor(protected myService: MyService) {} protected myForm: FormGroup; protected doCommonThingWithForm() { // 通用表单逻辑实现 } } // 派生类 export class MyDerivedComponent extends MyComponentBase { // 直接接收DI注入的服务,传递给基类 constructor(myService: MyService) { super(myService); } // 注意:Angular生命周期钩子是小驼峰的ngOnInit,大写开头不会被触发 ngOnInit(): void { this.doCommonThingWithForm(); // 派生类自定义逻辑 } }
原理:Angular的DI系统会自动将MyService实例注入到派生类构造函数,你只需要把这个实例传递给基类即可。由于基类已将myService声明为protected,派生类可以直接通过this.myService访问该服务,无需重复声明。
方案2:基类添加@Injectable自动处理依赖
如果希望派生类无需手动传递依赖,可以给基类添加@Injectable装饰器,让Angular自动处理基类的依赖注入:
import { Injectable } from '@angular/core'; // 给基类添加@Injectable @Injectable() export class MyComponentBase { constructor(protected myService: MyService) {} protected myForm: FormGroup; protected doCommonThingWithForm() {} } // 派生类构造函数无需传递依赖 export class MyDerivedComponent extends MyComponentBase { constructor() { super(); } ngOnInit(): void { this.doCommonThingWithForm(); } }
注意:这种方式需要确保MyService在当前注入器层级中是可获取的,且基类的所有依赖都能被DI系统正确解析。
内容的提问来源于stack exchange,提问作者FunkMonkey33
相关产品推荐
相关产品推荐

