作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 angularJS2 开发一个项目,并使用 $http 和 observable 从 rest API 解析 JSON,这是我的代码。
服务:
getSingleKey(id:any){
var headers = new Headers();
headers.append('content-Type','application/json');
return this.http.get(
'http://192.168.1.59/keyapp/api/getKeyspiration/'+id+'.json'
).map(res => res.json());
组件:
private dataKey: Object = {};
this.keyService.getSingleKey(this.id)
.subscribe(
data=>
{
console.log(data.data),
this.dataKey=data.data
},
error=>console.log(error)
);
console.log(this.dataKey);
我收到以下回复:
GET
localhost/keyapp/api/getKeyspiration/15.json [HTTP/1.1 200 OK 398ms]
//console.log(data.data) 的响应
Object { k_id: 15, k_u_id: 5, k_type: 3, k_title: "vaibhav", k_text: "", k_data: "2024067187.png", k_thumb: "", k_added_date: "2016-11-24T06:10:23+0000" }
// response for console.log(this.dataKey)
Object { }
简而言之,我正在获取响应数据,但我如何才能将响应对象分配给我的类对象,我的代码中是否缺少某些内容。预先感谢您的帮助。
最佳答案
正如@JBNizet 在评论部分提到的问题,您正在记录一个您期望异步的值。
您的 getSingleKey()
方法是异步方法,这意味着您无法猜测响应何时到达(网络速度等)。
您必须在异步函数的回调中对响应执行您计划执行的任何操作:
private dataKey: Object = {};
this.keyService.getSingleKey(this.id)
.subscribe(
data=>
{
console.log(data.data),
this.dataKey=data.data;
console.log(this.dataKey); //will be defined since it is in the async functions
//callback scope, so do whatever you want to do with this.dataKey here
},
error=>console.log(error)
);
console.log(this.dataKey); //will be undefined since it is out of the async functions callback scope
关于angular - 如何将 AngularJS2 响应对象分配给类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41542858/
我是一名优秀的程序员,十分优秀!