Getting instance of service without constructor injection

前端 未结 4 1865
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 05:21

I have a @Injectable service defined in bootstrap. I want to get the instance of the service without using constructor injection. I tried using Reflective

4条回答
  •  独厮守ぢ
    2020-11-28 05:48

    Another approach would consist of defining a custom decorator (a CustomInjectable to set the metadata for dependency injection:

    export function CustomComponent(annotation: any) {
      return function (target: Function) {
    
        // DI configuration
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);
    
        Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);
    
        // Component annotations / metadata
        var annotations = Reflect.getOwnMetadata('annotations', target);
        annotations = annotations || [];
        annotations.push(annotation);
        Reflect.defineMetadata('annotations', annotations, target);
      }
    }
    

    It will leverage the metadata from the parent constructor instead of its own ones. You can use it on the child class:

    @Injectable()
    export class SomeService {
      constructor(protected http:Http) {
      }
    }
    
    @Component()
    export class BaseComponent {
      constructor(private service:SomeService) {
      }
    }
    
    @CustomComponent({
      (...)
    })
    export class TestComponent extends BaseComponent {
      constructor() {
        super(arguments);
      }
    
      test() {
        console.log('http = '+this.http);
      }
    }
    

    See this question for more details:

    • Angular2 use imported libs from base class

提交回复
热议问题