简体   繁体   中英

Why to import { HttpClientModule } in app.module.ts

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

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 ie 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM