1

I'm developing a Angular 2 application to access REST API endpoints and show the data to users. I tested REST API endpoints in Postman and those are working well. When i'm accessing a GET endpoint from Angular i'm getting following error snippet.

Error: StaticInjectorError[Http]: 
StaticInjectorError[Http]: 
NullInjectorError: No provider for Http!
at _NullInjector.get (webpack-internal:///../../../core/esm5/core.js:1189)
at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477)
at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419)
at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290)
at resolveNgModuleDep (webpack-internal:///../../../core/esm5/core.js:11074)
at NgModuleRef_.get (webpack-internal:///../../../core/esm5/core.js:12306)
at resolveDep (webpack-internal:///../../../core/esm5/core.js:12804)

Tried by importing both Http and HttpModule like this top of the code as well.

import { HttpModule } from '@angular/http';
import {Http} from '@angular/http';

Following is my relevant code snippet for the get data function.

getData(){
    const url = 'http://localhost/laravel_app/public/api/getdata';
    this.http.get(url).subscribe(
      res => {
        const data = res.json();
        console.log(data);
        return data;
      }
    );
  }
CodeCanyon
  • 929
  • 2
  • 11
  • 36

4 Answers4

1

You need to add this code into your app.module.ts file.

import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';

imports: [
   BrowserModule,
   HttpModule       
]

Actually http is used in angular 2 but now in latest version of angular it used HttpClient.

Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

If you are using angular v5 version, import HttpClientModule in your app.module.ts after HttpModule.

imports: [
    HttpModule,
    HttpClientModule
]
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

you should import HttpModule in the module.ts file and the Http in the service where you are actually using it to make the api call.

Have a look here

arbghl
  • 358
  • 2
  • 14
-1

you can import this line app.module.ts

    import { HttpModule } from '@angular/http';

and write in

@NgModule({
   imports: [
    HttpModule,
   ]
 })
ashishdudhat
  • 180
  • 3
  • 9
  • Did like this. Then i'm getting this error - Uncaught Error: Unexpected value 'Http' imported by the module 'AppModule'. Please add a @NgModule annotation. – CodeCanyon Jan 09 '18 at 05:20
  • Finally it works. I have imported both Http and HttpModule. No need to import both as you have mentioned. – CodeCanyon Jan 09 '18 at 05:30