【问题标题】:No provider for HttpService没有 HttpService 的提供者
【发布时间】:2016-07-13 09:44:53
【问题描述】:

当我运行以下项目时出现错误:

没有 HttpService 的提供者! (AppComponent -> HttpService)

有人可以帮帮我吗?

我的应用组件:

    import {Component} from 'angular2/core';
import {HttpService} from "./htttp.service";

@Component({
  selector: 'my-app',
  template: `
  <div>
  <div class="input">
  <label for="title">Title</label>
  <input type="text" id="title" #title>
  </div>
    <div class="body">
  <label for="body">Body</label>
  <input type="text" id="body" #body>
  </div>
    <div class="user-id">
  <label for="user-id">User ID</label>
  <input type="text" id="user-id" #userid>
  </div>
  <button (click)="onPost(title.value, body.value, userid.value)">Post Data</button>
  <button (click)="onGetPosts()">Get All Posts</button>
  <p>Response: {{response | json}}</p>
  </div>,

  providers: [HttpService]
      `,
})
export class AppComponent {
  response: string;

  constructor(private _httpService: HttpService){}
  onGetPosts(){
    this._httpService.getPosts().subscribe(
      response => this.response=response,
      error => console.log(error)
    )
  }

}

HttpService:

import {Injectable} from 'angular2/core';
import {Http} from "angular2/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';

@Injectable()

export class HttpService{
  constructor(private _http:Http){}

  getPosts():Observable<any>{
    return this._http.get('http://jsonplaceholder.typicode.com/posts').map(res => res.json());
  }

}

和 boot.ts:

import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./app.component";
import {HTTP_PROVIDERS} from  "angular2/http";

bootstrap(AppComponent, [HTTP_PROVIDERS]);

问题出在哪里?

【问题讨论】:

  • 你的问题在这里 import {HttpService} from "./htttp.service"; 你有 3 thtttp 它应该只有 2
  • 谢谢!多么愚蠢的错误! :)
  • 不用担心。现在点击UP 按钮!谢谢!
  • 我做到了。它不起作用。我稍后再试

标签: angular httpservice angular2-providers


【解决方案1】:

应该是

import {HttpService} from "./http.service";

【讨论】:

    【解决方案2】:

    在声明提供者之前,您忘记关闭模板文字“反引号”。

    @Component({
      selector: 'my-app',
      template: `
      <div>
      <div class="input">
      <label for="title">Title</label>
      <input type="text" id="title" #title>
      </div>
        <div class="body">
      <label for="body">Body</label>
      <input type="text" id="body" #body>
      </div>
        <div class="user-id">
      <label for="user-id">User ID</label>
      <input type="text" id="user-id" #userid>
      </div>
      <button (click)="onPost(title.value, body.value, userid.value)">Post Data</button>
      <button (click)="onGetPosts()">Get All Posts</button>
      <p>Response: {{response | json}}</p>
      </div>`,
      providers: [HttpService]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-26
      • 2017-08-13
      • 2012-07-07
      • 2018-06-29
      • 2018-08-11
      • 2017-06-04
      • 2018-04-24
      • 2017-03-01
      相关资源
      最近更新 更多