使用Angular 2 Http从REST Web服务获取数据Http
问题描述:
我想从使用Angular 2 Http的REST Web服务获取数据。使用Angular 2 Http从REST Web服务获取数据Http
予先在调用它的客户端组件类的构造注入服务:
constructor (private _myService: MyService,
private route: ActivatedRoute,
private router: Router) {}
我添加调用为MyService的方法来从web服务获取数据的getData()方法:
getData(myArg: string) {
this._myService.fetchData(myArg)
.subscribe(data => this.jsonData = JSON.stringify(data),
error => alert(error),
() => console.log("Finished")
);
console.log('response ' + this.jsonData);
我调用客户端组件类的ngOnInit方法getData()方法(I正确导入并实现了的OnInit接口):
this.getData(this.myArg);
这里是为MyService服务:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MyService {
constructor (private _http: Http) {}
fetchData(myArg: string) {
return this._http.get("http://date.jsontest.com/").map(res => res.json());
}
}
我不设法获取数据,当我尝试在上面的getData()方法使用console.log('response ' + this.jsonData);
测试它,我在浏览器中得到response undefined
。
PS:jsonData是客户端组件类的字符串属性。
答
由于http请求是异步的,当您尝试将其记录到控制台时,将不会设置this.jsonData
。而是将该日志放入订阅回调中:
getData(myArg: string){
this._myService.fetchData(myArg)
.subscribe(data => {
this.jsonData = JSON.stringify(data)
console.log(this.jsonData);
},
error => alert(error),
() => console.log("Finished")
);
}