首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 2:属性注入而不是构造函数注入

Angular 2:属性注入而不是构造函数注入
EN

Stack Overflow用户
提问于 2017-02-13 18:21:01
回答 2查看 5.2K关注 0票数 14

我可以这样做吗:

代码语言:javascript
复制
export class BaseComponent {
protected config: IConfig;

@Inject(AppConfig) protected appConfig: AppConfig;

constructor() 
{ 
    this.config = this.appConfig.getConfig();    
}

而不是这样:

代码语言:javascript
复制
export class BaseComponent {
config: IConfig;

constructor(
    private appConfig: AppConfig,
    ) 
{ 
    this.config = appConfig.getConfig();    
}

目标是简化构造函数签名,这样所有子组件就不需要在构造函数中指定appConfig。因此,从BaseComponent继承的组件如下所示:

代码语言:javascript
复制
@Component({
    selector: 'sport-templates',
    templateUrl: 'templates.component.html',
    styleUrls: [ 'templates.component.scss' ],
    encapsulation: ViewEncapsulation.None
})
export class SportTemplates extends BaseComponent implements OnInit {

    constructor() {
        super();
    }

取而代之的是:

代码语言:javascript
复制
@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);
     }
EN

回答 2

Stack Overflow用户

发布于 2017-02-13 18:53:00

您可以这样做:

代码语言:javascript
复制
myService: MyService = this.injector.get(MyService);
constructor(private injector:Injector) {}

Injector位于@angular/core中

票数 1
EN

Stack Overflow用户

发布于 2017-02-13 18:42:44

不你不能这么做。当构造函数被调用时,可注入服务将被注入。

目标是简化构造函数签名。

不需要简化构造函数签名。为了提高可读性,您可以将它们写在多行中。

,以便所有子组件不需要在其构造函数中指定appConfig

在您的例子中,只有继承您的类的类才能访问它。但是如果你指子组件,那些在你的组件中使用的组件,他们不能访问父组件中的变量。你需要通过它们。

已更新

您的this.config在继承的组件中始终可见。不需要在SportTemplates组件中再次注入appConfig

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42201667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档