我可以这样做吗:
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);
}发布于 2017-02-13 18:53:00
您可以这样做:
myService: MyService = this.injector.get(MyService);
constructor(private injector:Injector) {}Injector位于@angular/core中
发布于 2017-02-13 18:42:44
不你不能这么做。当构造函数被调用时,可注入服务将被注入。
目标是简化构造函数签名。
不需要简化构造函数签名。为了提高可读性,您可以将它们写在多行中。
,以便所有子组件不需要在其构造函数中指定appConfig
在您的例子中,只有继承您的类的类才能访问它。但是如果你指子组件,那些在你的组件中使用的组件,他们不能访问父组件中的变量。你需要通过它们。
已更新
您的this.config在继承的组件中始终可见。不需要在SportTemplates组件中再次注入appConfig。
https://stackoverflow.com/questions/42201667
复制相似问题