1

I have been working on creating a service to make http requests and hence I'm using HttpClientModule given by Angular. I have data.serivce.ts file where the service is declared and I'm importing the HttpClient as shown below.

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

@Injectable()
export class DataService {

  constructor(private http:HttpClient) { 

  }

  validateLogin(){
    return this.http.get('https://someurl')
  }
}

Since I'm injecting the dependency of DataService in the providers array of the app.module.ts, I don't understand why I need to import the HttpClientModule again in the app.module.ts

1
  • Having imported HttpClientModule into the mainmodule, you can inject the HttpClient` into an application class like your service Commented Dec 23, 2018 at 5:22

3 Answers 3

2

You should look into how angular modules work. Your app.module.ts contains AppModule which is a root module. Every application has at least one module i.e. root module. If you import any module inside your AppModule then its (imported module) components will be accessible to every component of your application.

Thats why to make HttpClient available "everywhere" in the app:

import the HttpClientModule inside AppModule. Now you can use Services, Components etc defined inside HttpClientModule in your own services or components.

Sign up to request clarification or add additional context in comments.

Comments

0

For the variable type information you use on this line

constructor(private http:HttpClient)

Without that import, there would be an error since that type would be unknown.

1 Comment

I understood why to import it in my service(data.service.ts). But still not sure why the same import should there again in app.module.ts file.
0

In the Angular docs it says that the HttpClientModule, "Configures the dependency injector for HttpClient with supporting services for XSRF." So it looks like that's why it would be a prerequisite for using the HttpClient.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.