Inheritance and dependency injection

后端 未结 7 1416
时光说笑
时光说笑 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 05:04

    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.

    It's not absurd. This is how constructors and constructor injection works.

    Every injectable class has to declare the dependencies as constructor parameters and if the superclass also has dependencies these need to be listed in the subclass' constructor as well and passed along to the superclass with the super(dep1, dep2) call.

    Passing around an injector and acquiring dependencies imperatively has serious disadvantages.

    It hides dependencies which makes code harder to read.
    It violates expectations of one familiar with how Angular2 DI works.
    It breaks offline compilation that generates static code to replace declarative and imperative DI to improve performance and reduce code size.

提交回复
热议问题