Using Angular 7 & Typescript: I have a base class that uses a lot of services and child classes (about 40 sub-class) and I don't want to add those services in all subclass constructor and pass them to super()
but I still need to use those services in all subclass.
export class parentTool {
constructor(type: string, public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4){}
}
export class ChildTool1 extends parentTool {
constructor(public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4) {
super("tool1", service1, service2, service3, service4);
}
}
export class ChildTool2 extends parentTool {
constructor(public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4) {
super("tool2", service1, service2, service3, service4);
}
}
Yes, the first thing is to add the @Injectable decorator on each services you want to inject.
while injecting the service in your component if you miss the access modifier it will give you error as given below, but adding it as private or public will run fine.
I use to have the same problem so I end up doing manulay DI (dependency injection) by using injector
service
this static class use to store a refrence of injector service
export class AppInjector {
private static injector: Injector;
static setInjector(injector: Injector) {
AppInjector.injector = injector;
}
static getInjector(): Injector {
return AppInjector.injector;
}
}
at app module I set the injoctor service
export class AppModule {
constructor(injector:Injector){
AppInjector.setInjector(injector);// save a injector ref 💾
}
}
you need to store the service before you start do any DI (dependency injection)
in the base component
export class BaseComponent {
protected utilitiesService: UtilitiesService; // 👈 service
protected loggingService: LoggingService; // 👈 service
constructor() {
const injector = AppInjector.getInjector();
this.utilitiesService = injector.get(UtilitiesService); // 🌟 DI
this.loggingService = injector.get(LoggingService); // 🌟 DI
}
}
child class now have access to all service injected by the injector class 🎉🎉
export class ChildComponent extends BaseComponent {
constructor() {
super();
}
}
demo 🔥🔥
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