2017-09-13 138 views
0

我想从我的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结果:

enter image description here

我想要得到的是customer_delivery_city_addressenter image description here。我试图通过this.customer.customer_delivery_city_addressthis.cus_city变量,并将其显示到我的控制台console.log("City Address: " +this.cus_city),但我得到undefined结果。一切都很好,当我把它叫做我的HTML {{customer.customer_delivery_city_address}}。我仍然不知道如何将特定数据传输到我的TS文件。希望任何人都可以帮助我。先谢谢你。

+0

angular1 or angular2? –

+0

尝试this.customer [0] .customer_delivery_city_address – JayDeeEss

+0

我正在使用angular2。 – Patrick

回答

1

this.customer是一个数组而不是对象。按索引访问customer_delivery_city_address属性。

this.cus_city = this.customer[0].customer_delivery_city_address; 
console.log("City Address: " +this.cus_city) 
+0

非常感谢你!它为我工作。 – Patrick

+0

@帕特里克不错,一定要检查这个答案,如果这有帮助 –

2

我想接下来的回应是一个数组。你应该试试这个:

this.customer[0].customer_delivery_city_address 
+0

非常感谢你@Aman Jain – Patrick

1

我会这样做。

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_addressthis.customer是一个数组,如果你想第一个元素了,你可以做this.customer = data.customer [0]

<div> 
{{customer.customer_delivery_city_address}} 
</div>