没有 HttpService 的提供者

No provider for HttpService

当我 运行 以下项目时,我得到错误:

No provider for HttpService! (AppComponent -> HttpService)

有人可以帮我吗?

我的 AppComponent:

    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)
    )
  }

}

HTTP 服务:

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 "./http.service";

您在声明提供者之前忘记关闭模板文字 'back quote'。

@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]
})