Angular 2: property injection instead of constructor injection

Can i do this:

export class BaseComponent { protected config: IConfig; @Inject(AppConfig) protected appConfig: AppConfig; constructor() { this.config = this.appConfig.getConfig(); } 

instead of this:

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

The goal is to simplify the signature of the constructor, so all child components do not need to specify appConfig in their constructor. So the components that inherit from BaseComponent look like this:

 @Component({ selector: 'sport-templates', templateUrl: 'templates.component.html', styleUrls: [ 'templates.component.scss' ], encapsulation: ViewEncapsulation.None }) export class SportTemplates extends BaseComponent implements OnInit { constructor() { super(); } 

instead of this:

 @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); } 
+7
dependency-injection angular typescript
source share
2 answers

No, you cannot do this. An injection service will be introduced when the constructor is called.

The goal is to simplify the signature of the constructor.

There is no need to simplify the signature of the constructor. For readability, you can write them in several lines.

therefore, all child components do not need to specify appConfig in their Constructor

In your case, only classes that inherit your class will access it. But if you mean a child component, those used in your component, they cannot access the variables in the parent component. You need to pass them.

UPDATED

Your this.config always displayed in legacy components. There is no need to re-enter appConfig in the SportTemplates component.

0
source share

You can do it:

 myService: MyService = this.injector.get(MyService); constructor(private injector:Injector) {} 

The injector is located in the @ angular / core folder

0
source share

All Articles