Is there a way to inject a service into a class without having to declare it as a parameter on the constructor?
The usual way works just fine, I have no complains about it. I'm just trying to create a super class to handle some stuff witch depends on a service and I want it to be independent, I don't want to have any references to that service on child classes.
This is the usual way:
export class MyComponent {
constructor(private someService: SomeNpmInstalledService) {}
doSomething() {
this.someService.do();
}
}
That's what I'm looking for:
export class MyComponent {
@Some injection magic annotation here
private someService: SomeNpmInstalledService;
constructor() {}
doSomething() {
this.someService.do();
}
}
I'll try to explain the reason why I want this kind of functionality with the following example:
export class MyComponent extends MySuperClass {
constructor() {
super();
}
doSomething() {
super.someSuperClassFonctionality();
}
}
export class MySuperClass {
constructor(private someService: SomeNpmInstalledService) {}
someSuperClassFonctionality() {
someService.doStuff();
}
}
The above code gives an error because in my component, when I call super(), I have to pass the parameter defined on the constructor of my super class. But That's exactly what I don't want to do. I want my components to don't even know about the service that is used inside the super class.
Yes: use Injector. https://angular.io/api/core/Injector
import { Injector } from '@angular/core';
then in your constructor:
constructor(injector: Injector) {
let this.service = injector.get(ServiceToInject);
}
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