从JSON API获取特定数据
我想从我的JSON API获取特定数据,但我总是在我的控制台中获得undefine
。从JSON API获取特定数据
这里是我使用http get
让我的JSON API我的TS文件:
我的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
是一个数组而不是对象。按索引访问customer_delivery_city_address
属性。
this.cus_city = this.customer[0].customer_delivery_city_address;
console.log("City Address: " +this.cus_city)
非常感谢你!它为我工作。 – Patrick
@帕特里克不错,一定要检查这个答案,如果这有帮助 –
我想接下来的回应是一个数组。你应该试试这个:
this.customer[0].customer_delivery_city_address
非常感谢你@Aman Jain – Patrick
我会这样做。
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.customer_delivery_city_address时this.customer是一个数组,如果你想第一个元素了,你可以做this.customer = data.customer [0]。
<div>
{{customer.customer_delivery_city_address}}
</div>
angular1 or angular2? –
尝试this.customer [0] .customer_delivery_city_address – JayDeeEss
我正在使用angular2。 – Patrick