Angular 5 - Service provider injection in all components with extends

前端 未结 1 1218
春和景丽
春和景丽 2021-01-27 07:04

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

相关标签:
1条回答
  • 2021-01-27 07:29

    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.

    0 讨论(0)
提交回复
热议问题