Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 constructor signature, so all child component to not need to specify appConfig in their constructor. So the components that inherits from BaseComponent to 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 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(appConfig: AppConfig) {
        super(appConfig);
     }
like image 429
Nikola Yankov Avatar asked Feb 13 '17 10:02

Nikola Yankov


People also ask

What is difference between @inject and @injectable in Angular?

@Injectable() lets Angular know that a class can be used with the dependency injector. @Injectable() is not strictly required if the class has other Angular decorators on it or does not have any dependencies. What is important is that any class that is going to be injected with Angular is decorated.

Which is better setter injection or constructor injection?

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is a much bigger concern.

Why we inject services in constructor in Angular?

Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.

Which dependency injection is used in Angular 2?

In Angular 2, we inject dependency via constructor of the class. In the above code, we have injected the “NumListServcie” dependency in constructor and made the “numList” object of “NumListServcie” type.


1 Answers

You can do this:

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

The Injector is in @angular/core

like image 80
Mikael Kristensen Avatar answered Oct 12 '22 12:10

Mikael Kristensen