Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
Dblock247 Avatar asked Nov 17 '25 12:11

Dblock247


1 Answers

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.

like image 86
Günter Zöchbauer Avatar answered Nov 19 '25 09:11

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!