I encountered strange situation and want to discuss is it correct or not. (please also look for little question update at the end)
In angular 4.3 I have some abstract class which is extended by few angular components. It looks like:
export abstract class SidePanel {
protected prop1;
protected prop2;
protected method1() {
//...
};
}
@Component({
// ...
})
export class SidePanelOne extends SidePanel {
// body
}
@Component({
// ...
})
export class SidePanelTwo extends SidePanel {
// body
}
I want to add some common functionality in parent class SidePanel and that requires angular's Injector to be accessible. So I want to do something like this:
export abstract class SidePanel {
protected prop1;
protected prop2;
constructor(injector: Injector){
this.prop1 = injector.get(MyClassName);
}
protected method1() {
//...
};
}
To make it possible I could pass Injector from children:
@Component({
// ...
})
export class SidePanelOne extends SidePanel {
constructor(injector: Injector) {
super(injector);
}
//rest of body
}
But I don't want to do so because I have too many children and in that case I had to add Injector in all of those. So I found simple solution (but don't sure whether it's correct or not):
@Injectable()
export abstract class SidePanel {
protected prop1;
protected prop2;
constructor(injector: Injector){
this.prop1 = injector.get(MyClassName);
}
protected method1() {
//...
};
}
@Component({
// ...
})
export class SidePanelOne extends SidePanel {
private test() {
this.prop1.myClassMethod(); // works!
}
// rest of body
}
As a result my child classes (components) don't have to have their own constructor only to inject and pass Injector and everything works fine. But it looks strange to apply Injectable() decorator on abstract class.
Is it correct or not?
Thanks in advance for your opinions.
UPDATE 14.03:
As it turned out, for above situation it's possible to use 'empty' Component decorator instead of Injectable:
@Component({})
export abstract class SidePanel {
// body
}
It is confusing too: what component with empty metadata means, is it correct to use it and why all of the parameters are optional (even the selector)?