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 there. Any of my components would then extend that superclass but this approach does not work.
Simplified example:
export class AbstractComponent {
constructor(private myservice: MyService) {
// Inject the service I need for all components
}
}
export MyComponent extends AbstractComponent {
constructor(private anotherService: AnotherService) {
super(); // This gives an error as super constructor needs an argument
}
}
I could solve this by injecting MyService
within each and every component and use that argument for the super()
call but that's definetly some kind of absurd.
How to organize my components correctly so that they inherit a service from the super class?
new MyService()
instead of injecting gives you exactly the same result (except more efficient). If you want to share the same service instance across different services and/or components, this will not work. Every class will get anotherMyService
instance. – LeithmyService
. Found a solution that avoids this but adds more code to the derived classes... – Surfeit