Search code examples
javascriptangulartypescripthttpservice

HTTP service not working


This is my HttpService.ts

import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map';

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

    getData() {
        return this.http.get('http://blog_api.org/v1/posts')
            .map((response: Response) => response.json());
    }
}

This is my app.component.ts

import { Component } from '@angular/core';
import { HttpService } from '../app/services/HttpService'
@Component({
    selector: 'my-app',
    template: `Hello`,
})
export class AppComponent  {
    constructor (private httpService: HttpService) {};

    ngOnInit() {
        this.httpService.getData()
            .subscribe(
                data => console.log(data)
            )
    }
}

When I running app, I get error:

EXCEPTION: No provider for HttpService!


Solution

  • You must provide the HttpService in the model that loads the app.component.ts.

    In your case, as you are using app.component.ts, provide the http in app.module.ts. Something like:

    import { HttpService } from '../app/services/HttpService'
    
    @NgModule({
      ...
      providers: [
        ... 
        HttpService,
      ]
    })
    export class AppModule { }