2017-09-13 23 views
0

JSON APIから特定のデータを取得しようとしていますが、いつも私のコンソールにundefineがあります。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の結果は私のコンソールである:

enter image description here

ここ

は、私は私のJSON APIを取得するためにhttp getを使用して、私のTSファイルであります

私が入手したかったのは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またはangular2? –

+0

try 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_addressあなたが最初の要素を出したい場合が配列であるthis.customer は、あなたが行うことができますthis.customer = data.customer [0]

<div> 
{{customer.customer_delivery_city_address}} 
</div> 
関連する問題