HttpClient 在 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)

In Your 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并在"根"或 AppModule 提供程序中提供。

它实际上不是HttpClient .

你打电话

console.log(this.config);

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

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

你可能想要

console.dir(config);

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

(此外,对对象使用 console.dir()

相关内容

最新更新