Injecting http in a service gives "No provider for Http!" error

Naresh picture Naresh · Apr 6, 2016 · Viewed 53k times · Source

Angular version: 2.0.0-beta.13

I am trying to inject http into a service:

@Injectable()
export class GithubService {
    ...
    constructor(private http: Http) {
    }
}

I have listed HTTP_PROVIDERS as a provider in the root component of my application, so this provider should be available to any component in my application:

@Component({
  providers: [HTTP_PROVIDERS],
})
export class AppComponent {}

However when I run this application, I get the following error:

EXCEPTION: Error: Uncaught (in promise): No provider for Http! (HttpReqComponent -> GithubService -> Http)

What am I doing wrong?

Edit

I changed providers to viewProviders and the error is now gone!

@Component({
  viewProviders: [HTTP_PROVIDERS],
})
export class AppComponent {}

However, I cannot explain why this is working. http is not being accessed by any view directly. It is only accessed inside GithubService. So why do I have to declare HTTP_PROVIDERS as a viewProvider?

Edit 2

Well, I moved the providers declaration from AppComponent down to the component where I need it and now it works! So there must be some quirk in declaring it at the root level.

@Component({
    providers: [HTTP_PROVIDERS, GithubService],
})
export class HttpReqComponent { }

Actually, both providers and viewProviders works. Turns out that viewProviders is actually more restrictive and provides better encapsulation of the component. See this article for details.

Answer

SoProgram picture SoProgram · Sep 28, 2016

Following this link

Angular2/http Exception no ConnectionBackend The answer of @abreneliere is correct for me while working with Angular 2 Quickstart (https://angular.io/guide/quickstart) and i was trying to add a service to a component.

The answer: File: app.module.ts Code:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from "@angular/http";
import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule, HttpModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }