[英]get the specific data from JSON API
我正在尝试从JSON API中获取特定数据,但是我总是在控制台中undefine
。
这是我的TS文件,我使用http get
来获取我的JSON API:
我的TS代码:
this.http.get('http://xxxxx.com/xxx/api.php/customer?filter=customer.customer_id,eq,21&transform=1')
.map(res => res.json())
.subscribe(data => {
this.customer = data.customer;
console.log(this.customer);
this.cus_city = this.customer.customer_delivery_city_address;
console.log("City Address: " +this.cus_city)
}, (err) => {
console.log("Something went wrong.");
});
这是我的控制台中的API结果:
我想得到的是customer_delivery_city_address
。 我试图将this.customer.customer_delivery_city_address
传递给this.cus_city
变量,并将其显示到我的控制台console.log("City Address: " +this.cus_city)
但是我得到的结果undefined
。 当我将其调用到HTML {{customer.customer_delivery_city_address}}
时,一切都很好。 我仍然不知道如何将特定数据保存到TS文件中。 希望任何人都可以帮助我。 先感谢您。
我认为即将到来的响应是一个数组。 您应该尝试这样:
this.customer[0].customer_delivery_city_address
this.customer
是一个数组,而不是一个对象。 通过索引访问customer_delivery_city_address
属性。
this.cus_city = this.customer[0].customer_delivery_city_address;
console.log("City Address: " +this.cus_city)
我会这样做。
customer: any;
getCustomer() {
return this.http.get('url').map((res: Response) => res.json());
}
loadCustomer(){
this.customer = [];
this.getCustomer().subscribe(d => {
for (var i = 0; i < d.length; i++) {
this.customer.push(d[i]);
}
}, err => {console.log(err)})
}
//在视野中
<div *ngFor="let c of customer">
{{c.customer_delivery_city_address}}
</div>
当this.customer是一个数组时,您正在尝试执行this.customer.customer_delivery_city_address ,如果要删除第一个元素,可以执行this.customer = data.customer [0] 。
<div>
{{customer.customer_delivery_city_address}}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.