10

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?

1
  • 1
    If the constructor in UploaderService does nothing, you could drop it altogether. Commented Oct 8, 2019 at 13:45

3 Answers 3

11

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

5

You need to pass through the injection

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

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

Comments

4

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);
  }
}

3 Comments

No, It's not a copy. we answered at same time;)
@MostafaSaadatnia - JonasMS's answer was posted before this one. Please check your facts.
@MostafaSaadatnia - For your information, you can see the exact time in a tooltip when the mouse is over "answered ... mins ago". JonasMH answered exactly 12 seconds earlier.

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.