[英]Error: Uncaught (in promise): TypeError: Cannot read property 'customerName' of undefined
My JSON file looks like this: 我的JSON文件如下所示:
{
"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: 我将它们显示在名为
list
的组件list
如下所示:
ts 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: 现在,我可以在模板中显示值(customerName,price ..):
But when i log
and see the same values(customerName, price ..), showing as undefined . 但是,当我
log
并看到相同的值(customerName,price ..)时,显示为undefined 。
I am unable find what went wrong. 我找不到出了什么问题。
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>
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
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 将“索引”更改为0,1,2分别获取第一个,第二个或第三个对象的customerName
this.customers is an array element. this.customers是一个数组元素。
Use forEach() to list each element. 使用forEach()列出每个元素。 Array.prototype.forEach()
Array.prototype.forEach()
this.customers.forEach(function(element) {
console.log(element.data.customerName);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.