Angular 2:属性注入而不是构造函数注入
发布时间:2020-12-17 07:21:02 所属栏目:安全 来源:网络整理
导读:我可以这样做: export class BaseComponent {protected config: IConfig;@Inject(AppConfig) protected appConfig: AppConfig;constructor() { this.config = this.appConfig.getConfig(); } 而不是这个: export class BaseComponent {config: IConfig;con
我可以这样做:
export class BaseComponent { protected config: IConfig; @Inject(AppConfig) protected appConfig: AppConfig; constructor() { this.config = this.appConfig.getConfig(); } 而不是这个: export class BaseComponent { config: IConfig; constructor( private appConfig: AppConfig,) { this.config = appConfig.getConfig(); } 目标是简化构造函数签名,因此所有子组件都不需要在其构造函数中指定appConfig.所以从BaseComponent继承的组件看起来像这样: @Component({ selector: 'sport-templates',templateUrl: 'templates.component.html',styleUrls: [ 'templates.component.scss' ],encapsulation: ViewEncapsulation.None }) export class SportTemplates extends BaseComponent implements OnInit { constructor() { super(); } 而是这样: @Component({ selector: 'sport-templates',encapsulation: ViewEncapsulation.None }) export class SportTemplates extends BaseComponent implements OnInit { constructor(appConfig: AppConfig) { super(appConfig); }
你可以这样做:
myService: MyService = this.injector.get(MyService); constructor(private injector:Injector) {} 注射器位于@ angular / core中 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |