使用Angular 2 Http从REST Web服务获取数据 [英] Fetching data from REST Web Service using Angular 2 Http
问题描述
我正在尝试使用Angular 2 Http从REST Web服务获取数据。
I'm trying to fetch data from a REST web service using Angular 2 Http.
我首先在调用的客户端组件类的构造函数中注入服务它:
I first inject the service in the constructor of the client component class that calls it:
constructor (private _myService: MyService,
private route: ActivatedRoute,
private router: Router) {}
我添加了一个getData()方法,该方法调用MyService方法从中获取数据网络服务:
I added a getData() method that calls a method of MyService to fetch data from the web service:
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()方法(我正确导入了实现了OnInit接口):
I call the getData() method in the ngOnInit method of the client component class (I correctly imported and implemented the OnInit interface):
this.getData(this.myArg);
以下是MyService服务:
Here is the MyService service:
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);
测试它,我得到响应undefined
在浏览器中。
I don't manage to fetch the data and when I try to test it using console.log('response ' + this.jsonData);
in the getData() method above, I get response undefined
in the browser.
PS:jsonData是客户端组件类的字符串属性。
PS: jsonData is a string attribute of the client component class.
推荐答案
由于http请求是异步的,因此在您尝试登录时不会设置 this.jsonData
控制台。而是将该日志放入订阅回调中:
Since http requests are async, this.jsonData
won't be set at the time where you try to log it to console. Instead put that log into the subscribe callback:
getData(myArg: string){
this._myService.fetchData(myArg)
.subscribe(data => {
this.jsonData = JSON.stringify(data)
console.log(this.jsonData);
},
error => alert(error),
() => console.log("Finished")
);
}
这篇关于使用Angular 2 Http从REST Web服务获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!