简体   繁体   English

TypeScript,带继承的Angular 2依赖注入

[英]TypeScript, Angular 2 Dependency Injection with Inheritance

I am using Angular 2 with TypeScript to construct a front end application. 我正在使用Angular 2和TypeScript构建前端应用程序。 I have a Generic Repository class: 我有一个Generic Repository类:

export abstract class Repository<T extends IEntity>
{    
  constructor(protected _http: Http) {}

  add(entity: T) {}
  delete(entity: T) {}
  list() {}
  get(id: number) {} 
  update(entity: T) {}
}

My Service class then extends my Generic Repository Class: 我的服务类然后扩展我的通用存储库类:

export class Service extends Repository<Entity>
{    
  constructor(protected _http: Http) {
    super(Http);
  }
}

The problem arises when I use dependency injection in the Parent class. 当我在Parent类中使用依赖注入时出现问题。 How do I then translate that to the child class? 然后我如何将其转换为子类?

When TypeScript compiles i get the following error: 当TypeScript编译时,我收到以下错误:

error TS2345: Argument of type 'typeof Http' is not assignable to parameter of type 'Http'.Property '_backend' is missing in type 'typeof Http' 错误TS2345:'typeof Http'类型的参数不能分配给'Http'类型的参数.Proofy'_ backend'类型'typeof Http'中缺少

Im not sure how to correct this error. 我不知道如何纠正这个错误。 Any help will be greatly appreciated. 任何帮助将不胜感激。

You just need to forward the instance you get passed (instead of the type as you did): 您只需转发您传递的实例(而不是您所做的类型):

export class Service extends Repository<Entity>
{    
  constructor(protected _http: Http) {
    super(_http);
  }
}

If no additional parameters are introduced in the subclass and also no additional code needs to be executed in the subclasses constructor, you can just omit the constructor. 如果子类中没有引入其他参数,并且也不需要在子类构造函数中执行其他代码,则可以省略构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM