gpt4 book ai didi

Angular 2 : Property injection instead of constructor injection

转载 作者:太空狗 更新时间:2023-10-29 17:11:05 27 4
gpt4 key购买 nike

我可以这样做吗:

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',
templateUrl: 'templates.component.html',
styleUrls: [ 'templates.component.scss' ],
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) {}

注入(inject)器在@angular/core

关于 Angular 2 : Property injection instead of constructor injection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42201667/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com