Inheritance and dependency injection

后端 未结 7 1407
时光说笑
时光说笑 2020-11-28 04:38

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

7条回答
  •  借酒劲吻你
    2020-11-28 05:11

    If parent class have been got from 3rd party plug-in (and you can't change the source) you can do this:

    import { Injector } from '@angular/core';
    
    export MyComponent extends AbstractComponent {
      constructor(
        protected injector: Injector,
        private anotherService: AnotherService
      ) {
        super(injector.get(MyService));
      }
    }
    

    or most better way (stay only one parameter in constructor):

    import { Injector } from '@angular/core';
    
    export MyComponent extends AbstractComponent {
      private anotherService: AnotherService;
    
      constructor(
        protected injector: Injector
      ) {
        super(injector.get(MyService));
        this.anotherService = injector.get(AnotherService);
      }
    }
    

提交回复
热议问题