Reputation: 101
I have a few components; I'm using Injector in constructor for encapsulation
import { Component, Injector, OnInit } from '@angular/core';
@Component({
selector: 'app-base',
templateUrl: './base.component.html',
styleUrls: ['./base.component.css'],
})
export class BaseComponent implements OnInit {
some = '';
constructor(injector: Injector) {
this.some = injector.get(this.some);
}
ngOnInit(): void {}
}
I'm using BaseComponent in other Component
import { BaseComponent } from '../base/base.component';
@Component({
selector: 'app-base-state',
templateUrl: './base-state.component.html',
styleUrls: ['./base-state.component.css'],
})
export class BaseStateComponent extends BaseComponent implements OnInit {
constructor(injector: Injector) {
super(injector);
}
ngOnInit(): void {}
}
BaseStateComponent I'm going to use in others component; Question is: Is there any way, to make injector in BaseComponent or BaseSateComponent Optional; I have a case, when I need a component, but I don't need an injector of it;
I know about feature
constructor(@Optional(), @Self() etc...);
But truly to say, I can't understand how it work's; I will be grateful if somebody can explain it Decorators;
Upvotes: 0
Views: 82
Reputation: 55443
The problem is that you want to use @Optional @Self to make injector optional. But, @optional @self works well with something that is injectable which you can provide in providers array at some level. In Angular, services are injectable. So you can use @Optional @Self @SkipSelf with services or something injectable
When you use constrocutor(private someService:SomeService), Angular will check whether SomeService is provided at componoent level means in @component's providers, if not, is it provided at Module Level, if not , is it provided at Root level? This way angular checks entire Injector tree.
When you use @Optional, it will not perform this check and so on....
Keep in mind that Injector resolves a token into a dependency.
Answer to your question
You can use optional parameter approach in typescript by simply providing ? mark next to parameter as shown below,
export class BaseComponent implements OnInit {
some = '';
constructor(private injector?: Injector) { // ? to make parameter optional
this.some = injector.get(this.some);
}
ngOnInit(): void {}
}
it also makes sense because you are using OOPs over classes.
Forked Stackblitz (Fixed some other issues also)
Upvotes: 1