简体   繁体   中英

get the specific data from JSON API

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.

I think the response which is coming is an array. You should try this:

this.customer[0].customer_delivery_city_address

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM