没有HttpService的提供者

时间:2016-07-13 09:44:53

标签: angular httpservice angular2-providers

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

  

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

}

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]);

问题出在哪里?

2 个答案:

答案 0 :(得分:2)

应该是

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

答案 1 :(得分:0)

在宣布提供商之前,您忘了关闭模板文字'后引号'。

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