Angular2 use imported libs from base class

后端 未结 1 427
半阙折子戏
半阙折子戏 2020-12-22 12:30

\"angular2\": \"2.0.0-beta.17\",

I\'d like to be able to import { Http, Response } from \'angular2/http\'; in my Base and use http

1条回答
  •  隐瞒了意图╮
    2020-12-22 12:52

    Using a parent class to define dependency injection of sub classes isn't supported in Angular2.

    The only thing you can do here if you want to use the http instance in the parent class:

    @Injectable()
    export class LoginService extends ApiServiceBase {
      constructor (http:Http) {
        super(http);
      }
    
      (...)
    }
    

    Edit

    A workaround would consist of defining a custom decorator to set the metadata for dependency injection:

    export function CustomInjectable(annotation: any) {
      return function (target: Function) {
        var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
        var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);
    
        Reflect.defineMetadata('design:paramtypes', parentAnnotations, 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 BaseService {
      constructor(protected http:Http) {
      }
    }
    
    @CustomInjectable()
    export class TestService extends BaseService {
      constructor() {
        super(arguments);
      }
    
      test() {
        console.log('http = '+this.http);
      }
    }
    

    See this plunkr: https://plnkr.co/edit/DIMyUB6rCE5d78dPlPZB?p=preview.

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