2017-09-13 177 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>