Reputation: 2204
My JSON file looks like this:
{
"total": 3,
"items": [
{
"id": "01",
"data": {
"customerName": "Jhon",
"description": "..some content..",
"price": "25000"
},
"status": "Yes"
},
{
"id": "02",
"data": {
"customerName": "Mark",
"description": "..some content..",
"price": "30000"
},
"status": "No"
},
{
"id": "03",
"data": {
"customerName": "Smith",
"description": "..some content..",
"price": "15000"
},
"status": "No"
}
]
}
I am displaying the them in an component called list
like this:
ts
import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contacts.service';
import { ICustomer } from '../models';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
public allCustomers: any = [];
public customers: any = [];
constructor(private myService: ContactService) { }
public async ngOnInit(): Promise<void> {
this.allCustomers = await this.myService.getCustomers('');
this.customers = this.allCustomers.items;
console.log( this.customers.data.customerName);
}
}
template
<div *ngFor="let customer of customers">
<p>{{customer.data.customerName}}</p>
<p>{{customer.data.price}}</p>
</div>
Now i am able to display the values(customerName, price ..) in template:
But when i log
and see the same values(customerName, price ..), showing as undefined.
I am unable find what went wrong.
Upvotes: 0
Views: 2247
Reputation: 151
this.customers is an array element.
Use forEach() to list each element. Array.prototype.forEach()
this.customers.forEach(function(element) {
console.log(element.data.customerName);
});
Upvotes: 0
Reputation: 462
you are returning an array of objects, knowing that array index starts from zero. This will work
console.log(this.customers[index].data.customerName);
Change the "index" to either 0,1,2 to get the customerName of the first,second or third object respectively
Upvotes: 0
Reputation: 20092
You have that error because you are accessing array value by object
console.log( this.customers.data.customerName); // this are array value
so if you want to see the data you have to do like this
console.log( this.customers[0].data.customerName); // this are array value
Upvotes: 1
Reputation: 222582
Use the Safe Navigation Operator to handle the undefined error
<div *ngFor="let customer of customers">
<p>{{customer?.data?.customerName}}</p>
<p>{{customer?.data?.price}}</p>
</div>
Upvotes: 1