HTTP 服务不工作

HTTP service not working

这是我的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());
    }
}

这是我的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)
            )
    }
}

当我 运行 应用程序时,出现错误:

EXCEPTION: No provider for HttpService!

您必须在加载 app.component.ts 的模型中提供 HttpService

在您的情况下,因为您使用的是 app.component.ts,请在 app.module.ts 中提供 http。类似于:

import { HttpService } from '../app/services/HttpService'

@NgModule({
  ...
  providers: [
    ... 
    HttpService,
  ]
})
export class AppModule { }

添加

providers: [HttpService]

在@Component 块中

在您的 AppModule 中,您应该做的是:

import {HttpService} from "...";
import {HttpModule} from "@angular/http";

@NgModule({
    bootstrap: [...],
    imports: [HttpModule],
    declarations: [...],
    entryComponents: [...],
    providers: [HttpService]
})
export default class AppModule{}