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

Nik*_*kov 10 dependency-injection typescript angular

我可以这样做:

export class BaseComponent {
protected config: IConfig;

@Inject(AppConfig) protected appConfig: AppConfig;

constructor() 
{ 
    this.config = this.appConfig.getConfig();    
}
Run Code Online (Sandbox Code Playgroud)

而不是这个:

export class BaseComponent {
config: IConfig;

constructor(
    private appConfig: AppConfig,
    ) 
{ 
    this.config = appConfig.getConfig();    
}
Run Code Online (Sandbox Code Playgroud)

目标是简化构造函数签名,因此所有子组件都不需要在其构造函数中指定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();
    }
Run Code Online (Sandbox Code Playgroud)

而是这样:

@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);
     }
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 0

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

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

无需简化构造函数签名。为了便于阅读,您可以将它们写成多行。

因此所有子组件都不需要在其构造函数中指定 appConfig

在您的情况下,只有继承您的类的类才能访问它。但是,如果您指的是组件中使用的子组件,则它们无法访问父组件中的变量。你需要通过它们。

更新

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