Dblock247
Dblock247

Reputation: 6725

TypeScript, Angular 2 Dependency Injection with Inheritance

I am using Angular 2 with TypeScript to construct a front end application. I have a Generic Repository class:

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. How do I then translate that to the child class?

When TypeScript compiles i get the following error:

error TS2345: Argument of type 'typeof Http' is not assignable to parameter of type 'Http'.Property '_backend' is missing in type 'typeof Http'

Im not sure how to correct this error. Any help will be greatly appreciated.

Upvotes: 3

Views: 3192

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

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.

Upvotes: 8

Related Questions