我正在编写一个角度2组件来测试Http服务,我有这个:
这是我的app.component.ts
import {Component} from 'angular2/core';
import {HttpService} from './http.service';
@Component({
selector: 'my-app',
template: `
<div>
<div class="input">
<label for="title">Title</label>
<input type="text" id="title" #title>
<p></p>
</div>
<div class="input">
<label for="body">Body</label>
<input type="text" id="body" #body>
<p></p>
</div>
<div class="input">
<label for="user-id">User ID</label>
<input type="text" id="user-id" #userId>
<p></p>
</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>
`,
directives: [HttpService]
})
export class AppComponent {
response: string;
constructor(private _httpService: HttpService) {};
onGetPosts() {
this._httpService.getPosts()
.subscribe(
response => this.response = response,
error => console.log(error)
)
}
}
答案 0 :(得分:1)
事实证明,当我将HttpService包含在提供者中作为提供者时,我将HttpService作为指令包含在我的组件装饰器中
<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() {