在服务中使用HttpClient时在Angular中引发错误

时间:2019-06-07 19:31:16

标签: angular

我正在尝试在服务的角度6中使用HttpClient,如下所示:

auth.service.ts

constructor(private http: HttpClient, public dataService: DataService, private config: AppConfig) {
        console.log(this.config);
    }

http:HttpClient是我收到以下错误的原因。当我删除此错误时。我不确定为什么会出现此错误。

core.js:1521 ERROR TypeError: Cannot read property 'length' of null
    at http.js:108
    at Array.forEach (<anonymous>)
    at HttpHeaders.lazyInit (http.js:102)
    at HttpHeaders.init (http.js:166)
    at HttpHeaders.forEach (http.js:235)
    at Observable._subscribe (http.js:1445)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at subscribeTo.js:21
    at subscribeToResult (subscribeToResult.js:6)

2 个答案:

答案 0 :(得分:1)

在您的app.module.ts中:

在导入数组下导入HttpClientModule,

import { HttpClientModule } from '@angular/common/http';


@NgModule({
   imports: [ ..., HttpClientModule, ...]  // import here

现在您可以在服务中注入HttpClient:

import { HttpClient } from '@angular/common/http';

 ...............
 constructor(private http: HttpClient, public dataService: DataService, private 
 config: AppConfig) {
       console.log(this.config);
  }

确保您的服务是Injectable并在“ root”或AppModule提供程序中提供。

答案 1 :(得分:0)

实际上不是HttpClient

您致电

console.log(this.config);

在构造函数中,但将config 作为参数传递给 constructor()

将参数传递给constructor()并不会自动设置其类似名称的this.对应对象。

您可能想要

console.dir(config);

this.config = config;
console.dir(this.config);

(此外,将console.dir()用于对象。)