I am following this fundamental tutorial on Angular about Http.
As one can see in the "Setup: Installing the module" section, they import the HttpClientModule as follow:
import {HttpClientModule} from '@angular/common/http';
When I try this in my project, I get the following error: "Cannot find module '@angular/common/http'".
I have tried importing the following module, as follow:
import { HttpModule } from '@angular/http';
And then my imports section:
imports: [ HttpModule ],
The problem now is, I cannot inject this HttpModule into my service object, and I get the following error: "Cannot find module HttpModule".
Here is my service class:
import { Injectable, OnInit } from '@angular/core'; //Custom Models import { Feed } from '../Models/Feed'; @Injectable() export class FeedsService { constructor(private httpClient: HttpModule) {} }
What am I doing wrong?
Update All I should have done when I realized I could not import the module as per the tutorial, was to run the npm update
command, to update all my packages.
Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http . The HTTP client service offers the following major features. The ability to request typed response objects. Streamlined error handling. Testability features.
This likely means that the library ( @angular/common/http ) which declares HttpClient has not been processed correctly by ngcc , or is not compatible with Angular Ivy . Check if a newer version of the library is available, and update if so.
Descriptionlink. HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.
Important: HttpClientModule
is for Angular 4.3.0 and above. Check @Maximus' comments and @Pengyy's answer for more info.
You need to inject HttpClient
in your component/service not the module. If you import HttpClientModule
in your @NgModule
// app.module.ts: import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; // Import HttpClientModule from @angular/common/http import {HttpClientModule} from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, // Include it under 'imports' in your application module // after BrowserModule. HttpClientModule, ], }) export class MyAppModule {}
So change
constructor(private httpClient: HttpModule) {}
to
constructor(private httpClient: HttpClient) {}
as it's been written in the documentation
However, since you imported the HttpModule
you need to inject constructor(private httpClient: Http)
as @Maximus stated in the comments and @Pengyy in this answer.
And for more info on differences between HttpModule
and HttpClientModule
, check this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With