Inherit Dependency injection

前端 未结 2 1047
面向向阳花
面向向阳花 2021-01-21 20:31

I want to create a generic api service in order to make model-related services easier to create:

export abstract class ModelService {

    constructor(p         


        
相关标签:
2条回答
  • 2021-01-21 20:51

    For child class that doesn't introduce extra dependencies and doesn't need its own constructor it is

    @Injectable()
    export abstract class ModelService<T> {...}
    
    export class FooService extends ModelService<Foo>{
    
    }
    

    @Injectable() decorator is needed for parent class (if it uses type annotation and not @Inject). No @Injectable() decorator is needed for child class.

    For children classes that may have their own dependencies and thus need own constructors the dependencies should be explicitly passed to super (see the other answer). In JavaScript, rest operator and @Inject may be used to skip some tautology, but for TypeScript it is safe to enumerate all constructor parameters explicitly.

    0 讨论(0)
  • 2021-01-21 21:00

    The constructor needs to repeat the dependencies and then passed to the super class using super(...)

    @Injectabe()
    export class FooService extends ModelService<Foo>{
        constructor(apiService: ApiService) {
          super(apiService);
            //ApiService is a service that wraps Http and adds signature , auth and serialization.
        }
    }
    

    This is not an Angular2 requirement or limitation, that's how constructors work in TypeScript.

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