I have class parent
and child
. The child
class extends parent
. I need to @Inject
injectable class service
to parent
because all child
's using it. How I can do it?
You can inject any service or class from parent with Injector
class, you need to inject the Injector
class from child and pass it to the parent by super(injector)
so parent can inject your reusable services from the injector coming from child.
Parent class :
export class BaseComponent implements OnInit {
protected myService: MyService
constructor(injector: Injector) {
this.myService = injector.get(MyService)
}
ngOnInit() {
console.log('ngOnInit from Base');
}
}
Child class :
export class AppComponent extends BaseComponent {
constructor(injector: Injector) {
super(injector)
}
ngOnInit() {
super.ngOnInit()
this.myService.getUsers()
}
}
Using this way you do not want to inject each services from child to pass one by one to parent, the above way is more efficient to inject from parent.
You can't inject a dependency into a parent class because Angular does not instantiate it for you. It creates an instance of your child class, which effectively initialises the parent class too (this isn't terribly accurate, as classes are just syntactic sugar, but it's suitable for this discussion).
One common solution is to just set up the child classes to be injectable and then pass the dependencies up using super
. e.g.:
class Parent {
constructor(protected someService: SomeService) { }
}
@Injectable()
class Child extends Parent {
constructor(someService: SomeService) {
super(someService);
}
}
If Parent
doesn't actually need the dependency itself, you're better off just using @Injectable()
on your child classes, which could have their own private reference to the dependency.
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