[英]How can I select both test objects in my JSON string and map them to my interface?
Question 题
How can I select both test objects in my JSON string and map them to my interface called Test
? 如何在JSON字符串中选择两个测试对象并将它们映射到名为
Test
接口? And is it possible that my property in the interface isnt called some_name
? 而且接口中的我的属性可能不是
some_name
吗?
Problem 问题
Im trying to map my JSON
objects to the Test
interface, but it does not work. 我试图将我的
JSON
对象映射到Test
接口,但是它不起作用。 The getTests
in the component always returns undefined for 组件中的
getTests
始终为以下对象返回未定义
I guess the reason is that there is a parent named test , but res.json().data should return only the both objects test 1 and test 2 . 我猜这是因为有一个名为test的父对象,但是res.json()。data应该只返回两个对象test 1和test 2 。
JSON JSON格式
{"test":[{"some_name":"test 1"},{"some_name":"test 2"}]}
Service Method 服务方式
getTests() {
return this.http.get(this.baseUrl + "/something")
.map(res => <Array<Test>> res.json().data)
.catch(this.handleError);
}
Component 零件
this.myService.getTests()
.subscribe(
tests => this.tests = tests,
error => this.errorMessage = <any>error);
From what I see there is no data
property in the JSON content you receive. 从我看到的内容来看,您收到的JSON内容中没有
data
属性。
res.json()
returns an object containing a test
property which is an array. res.json()
返回包含test
属性的对象,该属性是一个数组。 You should use .map(res => <Array<Test>> res.json().test)
instead to get the array. 您应该使用
.map(res => <Array<Test>> res.json().test)
来获取数组。
Thierry 蒂埃里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.