Coder
Coder

Reputation: 131

HttpClient throwing error in Angular when used in service

I am trying to use HttpClient in angular 6 in my service as follows:

auth.service.ts

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

This http:HttpClient is the reason I am getting the following error. When I remove this, the error goes. I am not sure why this error is coming.

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)

Upvotes: 0

Views: 408

Answers (2)

nircraft
nircraft

Reputation: 8478

In Your app.module.ts:

import HttpClientModule, under imports array:

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


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

And now you can inject HttpClient in your service:

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

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

Make sure your service is Injectable and provided in 'root' or in the AppModule providers.

Upvotes: 1

msanford
msanford

Reputation: 12247

It's not actually HttpClient.

You call

console.log(this.config);

in the constructor, but pass config as a parameter to constructor().

Passing parameters to the constructor() doesn't automatically set their similarly-named this. counterpart.

You probably want

console.dir(config);

or

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

(Also, use console.dir() for objects.)

Upvotes: 0

Related Questions