Inheritance and dependency injection

后端 未结 7 1312
时光说笑
时光说笑 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:19

    Instead of injecting a service that has all the other services as dependencies, like so:

    class ProviderService {
        constructor(private service1: Service1, private service2: Service2) {}
    }
    
    class BaseComponent {
        constructor(protected providerService: ProviderService) {}
    
        ngOnInit() {
            // Access to all application services with providerService
            this.providerService.service1
        }
    }
    
    class DerivedComponent extends BaseComponent {
        ngOnInit() {
            // Access to all application services with providerService
            this.providerService.service1
        }
    }
    

    I would skip this extra step and simply add inject all the services in the BaseComponent, like so:

    class BaseComponent {
        constructor(protected service1: Service1, protected service2: Service2) {}
    }
    
    class DerivedComponent extends BaseComponent {
        ngOnInit() {
            this.service1;
            this.service2;
        }
    }
    

    This technique assumes 2 things:

    1. Your concern is entirely related to components inheritance. Most likely, the reason you landed on this question is because of the overwhelming amount of non-dry (WET?) code you need to repeat in each derived class. If you want to benefits of a single entry point for all your components and services, you will need to do the extra step.

    2. Every component extends the BaseComponent

    There is also a disadvantage if you decide use the constructor of a derived class, as you will need to call super() and pass in all the dependencies. Although I don't really see a use case that necessitates the use of constructor instead of ngOnInit, it is entirely possible that such a use case exists.

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