HTTP服务无法正常工作

时间:2016-12-12 14:30:52

标签: javascript angular typescript httpservice

这是我的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:没有HttpService的提供者!

3 个答案:

答案 0 :(得分:1)

在AppModule中你应该这样做:

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

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

答案 1 :(得分:0)

您必须在加载HttpService

的模型中提供app.component.ts

在您的情况下,当您使用app.component.ts时,请在http中提供app.module.ts。类似的东西:

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

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

答案 2 :(得分:0)

添加

  

提供者:[HttpService]

@Component块中的

相关问题