Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - Cannot find name 'HttpClient'

Tags:

angular

I'm trying to access a JSON feed but after making the changes from the documentation I get the following error

"Cannot find name 'HttpClient'"

I've looked over the tutorial a few times but I'm struggling to find why I get this error.

My component where I perform the Http request.

rooms.parent.component.ts

import { Component, OnInit } from '@angular/core';  @Component({  /.../ })  export class RoomParentComponent implements OnInit {   results: string[];    // Inject HttpClient into your component or service.   constructor(private http: HttpClient) {}    ngOnInit(): void {     // Make the HTTP request:     this.http.get(/.../).subscribe(data => {       this.results = data;     });   } } 

app.module.ts

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import {HttpClientModule} from '@angular/common/http'; import { AppComponent } from './app.component'; import { RoomParentComponent } from './rooms.parent.component';  @NgModule({   declarations: [     AppComponent,     RoomParentComponent   ],   imports: [     BrowserModule,     HttpClientModule,   ],   providers: [],   bootstrap: [AppComponent] })  export class AppModule { } 

How do I resolve the above error and inject the HttpClient into the constructor?

Edit: My Angular version is 4.3.2

like image 703
Joshua Duxbury Avatar asked Jul 28 '17 14:07

Joshua Duxbury


People also ask

How does Angular connect to backend?

AJAX enables the communication with the backend / servers without refreshing the page. As AngularJS also used for single page applications. it provides built in support for AJAX communication with server. Create a service where we will create function send http requests to the server.


1 Answers

HttpClient got introduced in Angular 4.3.0 version. Also you have to make sure you have imported & injected HttpClientModule in your main AppModule's imports metadata.

// Import HttpClientModule from @angular/common/http in AppModule import {HttpClientModule} from '@angular/common/http';   //in place where you wanted to use `HttpClient` import { HttpClient } from '@angular/common/http'; 
like image 61
Pankaj Parkar Avatar answered Sep 27 '22 22:09

Pankaj Parkar