作者:痴情被撕碎的阳光 | 来源:互联网 | 2022-12-24 11:41
我正在写一个包含httpClient的基类。它用于进行REST api调用。如果在构造函数中定义了httpClient变量,则设置正确,但在私有变量中则未设置。
这是我的示例代码:
@Injectable()
export class MyBaseClass implements {
private httpClient = HttpClient
constructor(
private httpClient2: HttpClient
) {
console.log("httpClient2", httpClient2)
console.log("httpClient2.get", httpClient2.get)
}
callApi() {
console.log("httpClient", this.httpClient)
console.log("httpClient.get", this.httpClient.get)
}
}
构造函数输出:
callApi输出:
如您所见,两个变量并不相同,并且httpClient的get属性未定义。
我会在整个类中使用构造函数中的变量,但是我想要扩展此类,而在构造函数中使用变量并不方便。
任何帮助/建议将不胜感激。
谢谢,
将
1> David..:
如果您确实不想在基类的构造函数中注入服务,则还有另一种选择。
1.声明一个包含对注入器的引用的全局变量,并将其分配到您的模块中(或其他位置,在调用基类的构造函数之前)
import {Injector} from '@angular/core';
export let InjectorInstance: Injector;
export class AppModule
{
constructor(private injector: Injector)
{
InjectorInstance = this.injector;
}
}
2然后您可以在基类中像这样使用它
import {InjectorInstance} from '../app.module';
export class MyBaseClass
{
private httpClient : HttpClient:
constructor()
{
this.httpClient = InjectorInstance.get(HttpClient);
}
}