gpt4 book ai didi

angular - 如何在 Typescript 类中创建 Angular 5 HttpClient 实例

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:12 25 4
gpt4 key购买 nike

我正在编写一个包含 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)
}
}

构造函数输出: enter image description here

callApi 输出: enter image description here

如您所见,这两个变量不相同,并且 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com