![](/img/trans.png)
[英]TypeScript - http.get().subscribe() --> not setting variable
[英]Angular 2 HTTP GET with TypeScript: variable empty after subscribe
我正在尝试在服务中调用HTTP GET方法,我的问题是我无法正确保存响应。
在我的app.component.ts中:
marker: any;
...
this.formService.getMarker()
.subscribe(( marker: Marker[]) => {
this.marker = marker;
console.log(this.marker); // I get output from db
});
console.log(this.marker); // I get undefined
在我的app.service.ts中:
getMarker(){
return this.http.get('http://localhost:3002/marker')
.map(res => res.text());
}
如何正确保存API调用的响应,以便可以在组件中使用它?
@Component({...})
class MarkerComponent(){
marker: any;
getDataFromServer(){
let _self = this;
this.formService.getMarker()
.subscribe(( marker: Marker[]) => {
_self.marker = marker;
_self.cotherFunction(); // this run after the response
});
this.otherFunction() // this run after request
}
otherFunction(){
console.log(this.marker);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.