I\'m kinda new with Angular and I\'m trying to build my app around it, but I\'m having some troubles when injecting services in my Components.
I\'ve added a 3rd party mo
In order for child class to have additional dependencies, it should list parent's dependencies as well and pass them to super
:
export class PostsComponent extends DefaultComponent {
...
constructor(
translator: TranslateService,
cookieService: CookieService,
private postService: PostService
) {
super(translator, cookieService);
}
...
}
Parent's dependencies should have no visibility modifier because they are already assigned to instance in parent constructor.
In case there are many dependencies, parent class can be refactored to use Injector
in constructor to get them, Injector
will be the only dependency that needs to be passed to super
. If there is a possibility that list of parent's dependencies will be extended in future, it may be reasonable to use Injector
right away.
There is no other good way around. This boilerplate code is the price for trouble-free Angular experience. Any other way can currently be considered a hack.
There is always a chance that a list of parent dependencies is too big. In this case there will always be boilerplate code because a component should contain business logic for switching languages, while it's role is presentation logic (notice that language choice in ngOnInit
makes it impossible to switch languages without component tree recompilation, which is potential design flaw). It is preferable to merge TranslateService
and CookieService
into custom service that will be responsible for switching languages. This is an application of composition over inheritance principle.