super() 中的打字稿依赖注入

Mos*_*nia 5 inheritance dependency-injection superclass typescript angular

我有一个名为 restService 的类,如下所示:

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

  private baseUrl: string;

  constructor(private http: HttpClient) {
    this.baseUrl = environment.jsonServerUrl;
  }
}
Run Code Online (Sandbox Code Playgroud)

我有另一个类扩展了名为 UploaderService 的 RestService 类,如下所示:

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

  constructor() {
    super(); // error occurred here!
  }
}
Run Code Online (Sandbox Code Playgroud)

但是当我编写 super 方法时发生了错误,因为 RestService 类在其构造函数中有依赖注入,我不知道如何将它注入到 super 中。我该如何解决?

Pac*_*ac0 6

您可以重复参数,如其他答案所示。

但是,当您有许多参数和扩展类时,还有另一种方法很方便:用于Injector获取基类中的依赖项。

然后,您只需要在派生类中重复“注入器”注入,当您在基类中注入许多服务而在派生类中注入的服务不多时,这可以节省大量空间和头脑。

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*sMH 5

你需要通过注射

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

  constructor(http: HttpClient) {
    super(http);
  }
}
Run Code Online (Sandbox Code Playgroud)


Fat*_*zli 4

超类的参数需要重复并传递给超类调用:

@Injectable({
    providedIn: 'root'
})
export class UploaderService extends RestService {
  constructor (http: HttpClient){
    super(http);
  }
}
Run Code Online (Sandbox Code Playgroud)