[英]Assign value returned by Http subscribe method in Angular2
I have an issue when I call my webservice in Angular2. 我在Angular2中调用Web服务时遇到问题。 My variable
this.arc
is always empty because the function get()
is asynchronous and it return directly the variable before webservice's response. 我的变量
this.arc
始终为空,因为函数get()
是异步的,它在Web服务响应之前直接返回该变量。
I don't know how to handle this. 我不知道该如何处理。 I saw some informations about
defer
but i think is not the best way. 我看到了一些有关
defer
信息,但我认为这不是最好的方法。
Thanks ! 谢谢 !
getArcs (lat,lng) {
var url = "http://localhost:8081/api/v1/arcs?lat="+lat+"&lng="+lng;
this.arcs = [];
/*var options = new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json;charset=UTF-8'
})
});*/
this.http.get(url)
.subscribe(
(data: any) => {
JSON.parse(data._body).forEach(arc => {
//console.log(new Arc(arc));
this.arcs.push(new Arc(arc)); //add arcs
});
console.log("send");
},
error => {
console.log("error during http request");
}
);
return this.arcs;
}
---- EDIT---- ----编辑----
I think the problem is at the call of the function : 我认为问题出在函数的调用上:
public getData (lat,lng) {
var closedArc = this.arcService.getArcs(lat,lng);
console.log(closedArc);
//this.showArc(closedArc);
}
Since your really need data in your getData()
function, you can move subscribe logic there, and let getArcs()
return an Observable. 由于您确实需要
getData()
函数中的数据,因此可以在其中移动订阅逻辑,并让getArcs()
返回一个Observable。 This is a good practice - let services return Observables and subscribe to them when you need data. 这是一个好习惯-让服务返回Observable,并在需要数据时订阅它们。
getArcs(lat, lng) {
var url = "http://localhost:8081/api/v1/arcs?lat=" + lat + "&lng=" + lng;
return this.http
.get(url)
.map(response => response.json()) // response has builtin method to parse json.
.map(arc => {
return new Arc(arc);
})
}
public getData(lat, lng) {
var closedArc;
this.arcService
.getArcs(lat, lng)
.subscribe(
arcs => closedArc = arcs, // success
error => console.log("error during http request"), // error
() => this.showArc(closedArc) // complete
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.