C-zar
C-zar

Reputation: 41

Angular 2 error NullInjectorError: No provider for Http

I am trying to read a json github service and I am getting an error NullInjectorError: No provider for Http!

I already to add providers all over the code but it is not working I dont know what is causing the error but know where it is happening i need some who can help to understand what is causing this

import { Injectable } from '@angular/core';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http, JsonpModule} from '@angular/http';
import { Observable} from 'rxjs'; 
import 'rxjs/add/operator/map';


@NgModule({

    imports: [     
          BrowserModule,
          HttpModule,
          JsonpModule,

        ]

  }) 

  @Injectable({
    providedIn:'root'
  })
 export class GithubService{
       constructor(private http:Http){

       }

       getUser(){
         const searchText ="js";
         const url = "http://api.github.com/search/users?q="+searchText;  
         this.http.get(url).subscribe(
           res=> {
             const data=res.json();
             console.log(data);
             return data;
           }
         )
       }
   }

Error I am getting:

AppComponent.html:7 ERROR NullInjectorError: StaticInjectorError(AppModule)[GithubService -> Http]: 
  StaticInjectorError(Platform: core)[GithubService -> Http]: 
    NullInjectorError: No provider for Http!

Upvotes: 1

Views: 3197

Answers (2)

Parth Lukhi
Parth Lukhi

Reputation: 181

Please follow below 2 steps,

Go to app.moudle.ts

  1. Add javascript import

    import { HttpModule, Http, JsonpModule} from '@angular/http';
    
  2. Add @ngModule Angular import

    imports: [
      BrowserModule,
      AppRoutingModule,
      HttpModule
    ],
    

Upvotes: 0

Bhagwat Tupe
Bhagwat Tupe

Reputation: 1943

Update: Angular v6+
From older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.

In your app.module.ts file change these

  1. import { HttpClientModule} from "@angular/common/http";
  2. Then update the modules imports[ ] array HttpClientModule

       @NgModule({
            imports: [
                BrowserModule,
                FormsModule, // if used
                HttpClientModule,
            ],
            declarations: [ AppComponent ],
            bootstrap:    [ AppComponent ]
        })
    

Upvotes: 8

Related Questions