I have a set of angular2 components that should all get some service injected. My first thought was that it would be best to create a super class and inject the service ther
Instead of injecting a service that has all the other services as dependencies, like so:
class ProviderService {
constructor(private service1: Service1, private service2: Service2) {}
}
class BaseComponent {
constructor(protected providerService: ProviderService) {}
ngOnInit() {
// Access to all application services with providerService
this.providerService.service1
}
}
class DerivedComponent extends BaseComponent {
ngOnInit() {
// Access to all application services with providerService
this.providerService.service1
}
}
I would skip this extra step and simply add inject all the services in the BaseComponent, like so:
class BaseComponent {
constructor(protected service1: Service1, protected service2: Service2) {}
}
class DerivedComponent extends BaseComponent {
ngOnInit() {
this.service1;
this.service2;
}
}
This technique assumes 2 things:
Your concern is entirely related to components inheritance. Most likely, the reason you landed on this question is because of the overwhelming amount of non-dry (WET?) code you need to repeat in each derived class. If you want to benefits of a single entry point for all your components and services, you will need to do the extra step.
Every component extends the BaseComponent
There is also a disadvantage if you decide use the constructor of a derived class, as you will need to call super()
and pass in all the dependencies. Although I don't really see a use case that necessitates the use of constructor
instead of ngOnInit
, it is entirely possible that such a use case exists.