gpt4 book ai didi

angular - 如何将 AngularJS2 响应对象分配给类对象

转载 作者:太空狗 更新时间:2023-10-29 19:29:57 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com