如何在 Typescript 类中创建 Angular 5 HttpClient 实例 [英] How to create Angular 5 HttpClient instance in Typescript class

查看:43
本文介绍了如何在 Typescript 类中创建 Angular 5 HttpClient 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含 httpClient 的基类.它用于进行 REST api 调用.如果在构造函数中定义了 httpClient 变量,则会正确设置,但不在私有变量中.

I'm writing a base class which contains the httpClient. It is used to make REST api calls. The httpClient variable is set correctly if defined in constructor, but not in private variable.

这是我的示例代码:

@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 属性未定义.

As you can see the two variables aren't the same and the get property of httpClient is undefined.

我会在整个类的构造函数中使用该变量,但我想要的是扩展这个类并且在构造函数中使用该变量并不方便.

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.

谢谢,

推荐答案

如果您真的不想在基类的构造函数中注入服务,还有另一种选择.

There is another option if you really don't want to inject the services in your base class' constructor.

1.声明一个包含对注入器的引用的全局变量,并将其分配到您的模块中(或在调用基类的构造函数之前的其他地方)

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)

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

export let InjectorInstance: Injector;

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

2然后你可以在你的基类中像这样使用它

2 Then you can use it like this in your base class

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

export class MyBaseClass  
{
    private httpClient : HttpClient:

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

}

这篇关于如何在 Typescript 类中创建 Angular 5 HttpClient 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆