[英]Whats the best way to cast JSON to generic Object[] in angular 2 typescript?
不知道这是否按预期工作,但是我想将json的对象转换为通用对象数组(这些对象是可延展的,并且可以根据我的URL进行更改)。 我应该改用JSON.parse(res.json()。data)吗? 谢谢。
return this.http.get(URL)
.toPromise()
.then(response => response.json().data as Object[])
.catch(this.handleError);
}
解决方案的问题是, Object
类型没有任何成员(通常的成员除外),因此任何尝试从JSON(例如id
等)访问特定属性的操作都会产生错误。
正确的方法是as any[]
:
return this.http.get(URL)
.toPromise()
.then(response => response.json().data as any[])
.catch(this.handleError);
}
这将使您可以访问JSON响应中的所有内容(以及JSON响应中没有的所有内容。在运行时会出现错误)。
最好将结果强制转换为特定类型,请参见如何将JSON对象强制转换为Typescript类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.