3

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.

1 Answer 1

8

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.

4
  • Thank you. May I ask a small follow up question. Does the child class inherit any classes that the parent class imports. For instance. The parent class imports http, response and headers. Do I have to import that into the parent class or no. Because it seems i get an error when I don t import http. error TS2304: Cannot find name 'Http'. Is that just because i have to pass on the dependency or do I have to to that will all the classes rxjs, response, headers etc?
    – Dblock247
    Apr 28, 2016 at 15:53
  • If the subclass is in a different file you need to import every class or other identifier you refer to in your code. If you use X somewhere in one of your *.ts file (where X is the name of a class that is declared in another file) you have to import that class to make it known inside your file. Not too easy to explain. Keep the follow-up questions coming if this doesn't make it clear ;-) Apr 28, 2016 at 15:56
  • What if _http needs to be private a private member of the parent so that child constructor takes no parameters?
    – Shawn
    Aug 29, 2016 at 14:25
  • @Shawn What do mean with parent? The super class? This is not possible. If you extend a class the sub class needs to provide the parameters for the super class. That's not related to Angular2 but TS only and similar in most class based languages. Aug 29, 2016 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.