当我运行以下项目时,出现错误:
没有 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)
)
}
}
服务:
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]);
问题出在哪里?