Reputation: 261
I am trying to get a specific data from my JSON API but I always get undefine
in my console.
Here is my TS file where I use http get
to get my JSON API:
My TS code:
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.");
});
Here is the API result in my console:
What I wanted to get is the customer_delivery_city_address
. I tried to pass the
this.customer.customer_delivery_city_address
to this.cus_city
variable and show it to my console console.log("City Address: " +this.cus_city)
but I am getting undefined
result. All is well when I call it to my HTML {{customer.customer_delivery_city_address}}
. I still have no idea how can I get the specific data to my TS file. Hope anyone can help me with this. Thank you in advance.
Upvotes: 0
Views: 209
Reputation: 26
I would do it in this way.
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)})
}
//in view
<div *ngFor="let c of customer">
{{c.customer_delivery_city_address}}
</div>
You are tring to do this.customer.customer_delivery_city_address when this.customer is an array, if you want the first element out you can do this.customer = data.customer[0].
<div>
{{customer.customer_delivery_city_address}}
</div>
Upvotes: 1
Reputation: 2612
I think the response which is coming is an array. You should try this:
this.customer[0].customer_delivery_city_address
Upvotes: 2
Reputation: 41445
this.customer
is an array not an object. access the customer_delivery_city_address
property by index.
this.cus_city = this.customer[0].customer_delivery_city_address;
console.log("City Address: " +this.cus_city)
Upvotes: 1