我正在学习Angular2并且有疑问:
我编写了一个发出HTTP请求并获取数据的服务。在我的组件中,我希望有一个使用此服务的方法,并且在该组件的HTML模板上,我有一个onClick调用此方法的按钮。
我的服务:
import {Injectable} from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class HomeService{
data: Object;
loading: boolean;
constructor(private http: Http){}
public myUrl = 'http://jsonplaceholder.typicode.com/users';
fetchData(): any {
this.loading = true;
this.http.request(this.myUrl)
.subscribe(
(res: Response) => {
this.data=res.json();
this.loading=false;
return this.data;
});
}
}
我的组件:
import {Component} from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import {HomeService} from './home.component.service';
@Component({
selector:'home',
templateUrl:'./app/Home/home.component.html',
providers:[HomeService],
directives: [ROUTER_DIRECTIVES]
})
export class Home {
data: Object;
constructor(){}
getData(){
}
}
我的模板:
<button type="button" (click)="getData()">Make Request</button>
<div *ngIf="loading">loading...</div>
<pre>{{data}}</pre>
如何实现此getData()方法?这是消费此类HTTP服务的正确方法吗?
答案 0 :(得分:1)
注入服务然后使用它:
export class Home {
data: Object;
constructor(private myService:HomeService){}
getData(){
this.data = this.myService.fetchData();
}
}