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);
}
@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.
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.
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.
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.
You can do this:
myService: MyService = this.injector.get(MyService);
constructor(private injector:Injector) {}
The Injector is in @angular/core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With