Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript dependency injection in super()

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?

like image 885
Mostafa Saadatnia Avatar asked Oct 08 '19 13:10

Mostafa Saadatnia


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);
  }
}
like image 111
Pac0 Avatar answered Oct 23 '22 23:10

Pac0


You need to pass through the injection

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

  constructor(http: HttpClient) {
    super(http);
  }
}
like image 5
JonasMH Avatar answered Oct 23 '22 23:10

JonasMH


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);
  }
}
like image 3
Fateme Fazli Avatar answered Oct 23 '22 23:10

Fateme Fazli