【问题标题】:HTTP service not workingHTTP 服务不工作
【发布时间】:2017-04-27 10:52:36
【问题描述】:

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

运行应用时出现错误:

例外:没有 HttpService 的提供者!

【问题讨论】:

  • 永远记得先用谷歌搜索错误信息。查询EXCEPTION: No provider for HttpService! 将显示大量现有问题。

标签: javascript angular typescript httpservice


【解决方案1】:

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

在您使用app.component.ts 的情况下,请在app.module.ts 中提供http。比如:

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

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

【讨论】:

    【解决方案2】:

    添加

    提供者:[HttpService]

    在@Component 块中

    【讨论】:

    • 如果你这样做,你最终会得到很多 http 实例。我认为最好在顶级模块中加载它并确保单个实例。
    【解决方案3】:

    在您的 AppModule 中您应该这样做:

    import {HttpService} from "...";
    import {HttpModule} from "@angular/http";
    
    @NgModule({
        bootstrap: [...],
        imports: [HttpModule],
        declarations: [...],
        entryComponents: [...],
        providers: [HttpService]
    })
    export default class AppModule{}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多