扩展Spartacus组件或服务时,能否使用Angular inject函数?
简化Spartacus组件/服务扩展时的依赖注入操作
在扩展Spartacus的组件或服务时,常规方式要在子类构造函数里重复父类的所有依赖项,才能添加新的依赖并传递给super(),这种写法繁琐且维护成本高。其实可以利用Angular的inject()函数来大幅简化这个流程。
原Spartacus类示例
export class CmsPageGuard { constructor( protected routingService: RoutingService, protected cmsService: CmsService, protected protectedRoutesGuard: ProtectedRoutesGuard, protected service: CmsPageGuardService, protected routingConfig: RoutingConfigService ) {} /*...*/ }
传统扩展方式(繁琐)
要添加新依赖WindowRef时,必须重复父类所有依赖:
export class CustomCmsPageGuard extends CmsPageGuard { constructor( protected routingService: RoutingService, protected cmsService: CmsService, protected protectedRoutesGuard: ProtectedRoutesGuard, protected service: CmsPageGuardService, protected routingConfig: RoutingConfigService, protected windowRef: WindowRef // 新增依赖 ) { super( routingService, cmsService, protectedRoutesGuard, service, routingConfig ); } someCustomLogicExampleUsingNewDependency() { if(this.windowRef.isBrowser()) { /* ... */ } } }
用inject()简化实现
从Angular 14开始,支持在类属性声明时直接使用inject()函数获取依赖,无需重写构造函数或重复父类依赖:
import { inject } from '@angular/core'; import { WindowRef } from '@spartacus/core'; export class CustomCmsPageGuard extends CmsPageGuard { // 直接通过inject()获取新依赖 protected windowRef = inject(WindowRef); someCustomLogicExampleUsingNewDependency() { if(this.windowRef.isBrowser()) { /* ... */ } } }
如果子类确实需要重写构造函数,只需调用无参的super(),再用inject()获取新依赖即可:
import { inject } from '@angular/core'; import { WindowRef } from '@spartacus/core'; export class CustomCmsPageGuard extends CmsPageGuard { protected windowRef: WindowRef; constructor() { super(); // 无需传递父类依赖,Angular会自动注入 this.windowRef = inject(WindowRef); } someCustomLogicExampleUsingNewDependency() { if(this.windowRef.isBrowser()) { /* ... */ } } }
原理说明
当子类未显式定义构造函数时,会自动继承父类构造函数,Angular会负责注入父类所需的全部依赖。子类的新依赖通过inject()直接获取,完全不需要维护冗长的父类依赖列表,既简化了代码,也降低了后续父类依赖变更时的维护成本。
内容的提问来源于stack exchange,提问作者Krzysztof Platis
相关产品推荐
相关产品推荐

