typescript dependency injection in super()

Viewed 1877

I have a class called restService like bellow:

@Injectable({
  providedIn: 'root'
})
export class RestService {

  private baseUrl: string;

  constructor(private http: HttpClient) {
    this.baseUrl = environment.jsonServerUrl;
  }
}

and I have another class extends RestService class called UploaderService like this:

@Injectable({
  providedIn: 'root'
})
export class UploaderService extends RestService {

  constructor() {
    super(); // error occurred here!
  }
}

but when I write super method error occurred because RestService Class has Dependency Injection in its constructor, and I don't know how can I inject that in the super. How can I fix that?

3 Answers

You can repeat the parameters, as shown in other answers.

There is another way, though, which is handy when you have many parameters and extended classes : use Injector to get the dependencies in the base class.

Then, you only need to repeat the "Injector" injection in derived classes, which can save a lot of space and mind sanity when you have many services to inject in base class, but not a lot in derived class.

import { MyService } from './my.service';
import { FooService } from './foo.service';
import { Injector } from '@angular/core';

export class Base {
    protected myService: MyService;
    protected fooService: FooService;

  constructor (protected injector: Injector) {
    this.myService = injector.get(MyService);
    this.fooService = injector.get(FooService);
  }
}

export class Derived extends Base {
  constructor(protected injector: Injector) {
    super(injector);
  }
}

You need to pass through the injection

@Injectable({
  providedIn: 'root'
})
export class UploaderService extends RestService {

  constructor(http: HttpClient) {
    super(http);
  }
}

The parameters of the super class need to be repeated and passed to the super call:

@Injectable({
    providedIn: 'root'
})
export class UploaderService extends RestService {
  constructor (http: HttpClient){
    super(http);
  }
}
Related