错误:未捕获(承诺):TypeError:无法读取未定义的属性“ customerName”

时间:2019-06-26 10:42:01

标签: javascript angular typescript angular6

我的 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"
        }
    ]
}

我将它们显示在名为list的组件中,如下所示:

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);
  }


}

模板

<div *ngFor="let customer of customers">
    <p>{{customer.data.customerName}}</p>
    <p>{{customer.data.price}}</p>
</div>

现在,我可以在模板中显示值(customerName,price ..):

enter image description here

但是当我log看到相同的值(customerName,price ..)时,显示为未定义

enter image description here

我找不到问题所在。

DEMO

4 个答案:

答案 0 :(得分:1)

使用安全导航操作符处理未定义的错误

<div *ngFor="let customer of customers">
    <p>{{customer?.data?.customerName}}</p>
    <p>{{customer?.data?.price}}</p>
</div>

答案 1 :(得分:1)

出现该错误是因为您正在按对象访问数组值

console.log( this.customers.data.customerName); // this are array value

因此,如果您想查看数据,就必须这样做

 console.log( this.customers[0].data.customerName); // this are array value

答案 2 :(得分:0)

您将返回一个对象数组,知道数组索引从零开始。 可以

console.log(this.customers[index].data.customerName);

将“索引”更改为0,1,2分别获取第一个,第二个或第三个对象的customerName

答案 3 :(得分:0)

this.customers 是一个数组元素。

使用forEach()列出每个元素。 Array.prototype.forEach()

this.customers.forEach(function(element) {
    console.log(element.data.customerName);
});