Inheritance and dependency injection

后端 未结 7 1399
时光说笑
时光说笑 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 all the services manually I created a class providing the services, e.g., it gets the services injected. This class is then injected into the derived classes and passed on to the base class.

    Derived class:

    @Component({
        ...
        providers: [ProviderService]
    })
    export class DerivedComponent extends BaseComponent {
        constructor(protected providerService: ProviderService) {
            super(providerService);
        }
    }
    

    Base class:

    export class BaseComponent {
        constructor(protected providerService: ProviderService) {
            // do something with providerService
        }
    }
    

    Service-providing class:

    @Injectable()
    export class ProviderService {
        constructor(private _apiService: ApiService, private _authService: AuthService) {
        }
    }
    

提交回复
热议问题