简体   繁体   English

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

[英]How to create Angular 5 HttpClient instance in Typescript class

I'm writing a base class which contains the httpClient. 我正在写一个包含httpClient的基类。 It is used to make REST api calls. 它用于进行REST api调用。 The httpClient variable is set correctly if defined in constructor, but not in private variable. 如果在构造函数中定义了httpClient变量,则设置正确,但在私有变量中则未设置。

Here's my sample code: 这是我的示例代码:

@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)
  }
}

constructor output: 构造函数输出: 在此处输入图片说明

callApi output: callApi输出: 在此处输入图片说明

As you can see the two variables aren't the same and the get property of httpClient is undefined. 如您所见,两个变量并不相同,并且httpClient的get属性未定义。

I would use the variable in the constructor throughout my class, but I what I want is to extend this class and having the variable in the constructor isn't convenient. 我会在整个类中使用构造函数中的变量,但是我想要扩展此类,而在构造函数中使用变量并不方便。

Any help/suggestions would be greatly appreciated. 任何帮助/建议将不胜感激。

Thanks, 谢谢,

Will

There is another option if you really don't want to inject the services in your base class' constructor. 如果您确实不想在基类的构造函数中注入服务,则还有另一种选择。

1. Declare a global variable containing a ref to the injector and assign it in your module (or somewhere else, before your base class'constructor is called) 1.声明一个包含对注入器的引用的全局变量,并将其分配到您的模块中(或其他位置,在调用基类的构造函数之前)

import {Injector} from '@angular/core';

export let InjectorInstance: Injector;

export class AppModule 
{
  constructor(private injector: Injector) 
  {
    InjectorInstance = this.injector;
  }
}

2 Then you can use it like this in your base class 2然后您可以在基类中像这样使用它

import {InjectorInstance} from '../app.module';

export class MyBaseClass  
{
    private httpClient : HttpClient:

    constructor()
    {
        this.httpClient = InjectorInstance.get<HttpClient>(HttpClient);
    }

}

The property httpClient on your class is simply being set to the HttpClient class constructor. 您类上的属性httpClient只是被设置为HttpClient类的构造函数。 If you need an instance of that class, you need to let Angular provide it to you via dependency injection like your httpClient2 property (ie as a parameter to your constructor). 如果需要该类的实例,则需要让Angular通过依赖注入将其提供给您,例如httpClient2属性(即,作为构造函数的参数)。

As a note, adding the private accessor to the parameter on the constructor is syntactic sugar that is doing the following: 注意,将private访问器添加到构造函数上的参数是语法糖,它可以执行以下操作:

class MyBaseClass {
    private httpClient2: HttpClient;

    constructor(httpClient2: HttpClient) {
        this.httpClient2 = httpClient2;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM