[英]typescript dependency injection in super()
I have a class called restService like bellow:我有一个名为 restService 的 class,如下所示:
@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:我有另一个 class 扩展 RestService class 称为 UploaderService ,如下所示:
@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.但是当我写超级方法时发生错误,因为 RestService Class 在其构造函数中有依赖注入,我不知道如何在超级中注入它。 How can I fix that?
我该如何解决?
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:超级class的参数需要重复传递给超级调用:
@Injectable({
providedIn: 'root'
})
export class UploaderService extends RestService {
constructor (http: HttpClient){
super(http);
}
}
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.但是,当您有许多参数和扩展类时,还有另一种方法很方便:使用
Injector
获取基础 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.然后,您只需要在派生类中重复“Injector”注入,当您在基类 class 中注入许多服务时,这可以节省大量空间和头脑清醒,但在派生类 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.