无法读取未定义的属性“first_name”

问题描述 投票:2回答:2

我有这个问题

无法读取未定义的属性“first_name”

这是我的HTML文件checkout.html

<ion-content>
      <ion-item>
        <ion-label>First Name</ion-label>
        <ion-input type="text" [(ngModel)]="newOrder.billing.first_name"></ion-input>
      </ion-item>
      
      ....
      
</ion-content>

这是我的ts文件checkout.ts

      this.storage.get("userLoginInfo").then((userLoginInfo) => {

      this.userInfo = userLoginInfo.user;

      let email = userLoginInfo.user.email;
      let id = userLoginInfo.user.id;

      this.WooCommerce.getAsync("customers/email/"+email).then((data) => {

        this.newOrder = JSON.parse(data.body).customer;

      })

    })

这是错误enter image description here的图像

javascript angular typescript ionic3 woocommerce-rest-api
2个回答
0
投票

您似乎正在异步加载newOrder。结果,您的页面被渲染,但async-task尚未完成。

您写道,您在构造函数中声明了this.newOrder.billing = {}。因此,他现在尝试在你的HTML中阅读newOrder.billing.first_namenewOrder.billing是一个空物体,所以那里没有first_name

只有当异步任务完成时,才会存在此数据。但是目前Angular在发生这种情况之前会抛出一个错误。

处理这种情况有两种非常常见的方法。

您可以告诉模板它不应该使用缺少的数据渲染零件

<ion-item *ngIf="newOrder.billing">
  <ion-label>First Name</ion-label>
  <ion-input type="text" [(ngModel)]="newOrder.billing.first_name"></ion-input>
</ion-item>

然后* ngIf将看到变量未定义且模板的那部分不会显示在DOM =>无错误:-) async-task完成后,变量不再是未定义的模板 - 部分将显示。

另一种方式(当你只是想显示数据时更常见)是使用 {{ newOrder.billing.first_name | async }} async-pipe也将确保Angular可以处理那个。与[ngModel]结合使用,我认为async-pipe不起作用。但它可能值得一试。

温暖的问候


0
投票

只需添加一个引号,我认为它会有所帮助。

<ion-input type="text" [(ngModel)]="newOrder?.billing.first_name"></ion-input>
© www.soinside.com 2019 - 2024. All rights reserved.