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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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 ;-)
What if _http needs to be private a private member of the parent so that child constructor takes no parameters?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.