作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在编写一个包含 httpClient 的基类。它用于进行 REST api 调用。如果在构造函数中而不是在私有(private)变量中定义,则 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)
}
}
如您所见,这两个变量不相同,并且 httpClient 的 get 属性未定义。
我会在整个类中使用构造函数中的变量,但我想要的是扩展此类并且在构造函数中使用变量并不方便。
如有任何帮助/建议,我们将不胜感激。
谢谢,
将
最佳答案
如果您真的不想在基类的构造函数中注入(inject)服务,还有另一种选择。
1.声明一个包含注入(inject)器引用的全局变量,并将其分配到您的模块中(或在其他地方,在调用基类的构造函数之前)
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>(HttpClient);
}
}
关于angular - 如何在 Typescript 类中创建 Angular 5 HttpClient 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49310134/
我是一名优秀的程序员,十分优秀!