Angular项目多重继承报错NG2003:无合适注入令牌问题求助
Angular 三层继承服务出现 NG2003 注入令牌错误的解决方法
错误原因
你给StoredDataService和HttpService都添加了@Injectable装饰器,Angular会将这两个类识别为可注入的服务,自动尝试解析构造函数的所有参数。但subPath和basePath是普通字符串参数,没有对应的注入令牌,Angular无法确定要注入什么值,因此抛出NG2003错误。
实际上这两个类是作为基类被继承的,不需要被Angular的依赖注入容器直接实例化,根本不需要@Injectable装饰器。
解决方案
1. 移除父类的@Injectable装饰器
只保留最终子类StoreStaffDesignationService的@Injectable,因为只有它需要被DI容器实例化。
修改后的完整代码
HttpService(基类)
export class HttpService<T> { protected baseUrl: string; protected basePath: string; protected http: HttpClient; constructor(basePath: string, http: HttpClient) { this.baseUrl = `${environment.BASE_URL}`; this.basePath = basePath; this.http = http; } }
StoredDataService(中间基类)
export class StoredDataService<T> extends HttpService<T> { protected subPath: string; constructor(subPath: string, http: HttpClient) { super(`store/${subPath}`, http); this.subPath = subPath; } }
StoreStaffDesignationService(最终服务类)
@Injectable({ providedIn: 'root' }) export class StoreStaffDesignationService extends StoredDataService<IStoreStaffDesignation> { constructor( override http: HttpClient ) { super('staff-designation', http); } }
额外说明
- 基类的构造函数参数如果不需要对外暴露,建议使用
protected修饰符,避免不必要的属性暴露,同时子类也能正常访问。 - 如果强行给基类保留
@Injectable,需要为字符串参数创建InjectionToken并手动注入,但这种方式会让代码冗余且不符合基类的设计初衷,不推荐。
内容的提问来源于stack exchange,提问作者hanushi-thana
相关产品推荐
相关产品推荐

