javascript - 无法读取未定义的属性 'first_name'

标签 javascript angular typescript ionic3 woocommerce-rest-api

我有这个问题

Cannot read property 'first_name' of undefined

这是我的 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

最佳答案

看来您正在异步加载 newOrder。 因此,您的页面已呈现,但异步任务尚未完成。

您写道,您在构造函数中声明了 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 中 => 没有错误:-) 一旦异步任务完成,变量不再是未定义的,模板部分将被显示。

另一种方式(当您只想显示数据时更常见)是使用 {{ newOrder.billing.first_name |异步}} 异步管道还将确保 Angular 可以处理那个。 结合 [ngModel] 我认为异步管道将无法工作。但这可能值得一试。

亲切的问候

关于javascript - 无法读取未定义的属性 'first_name',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52189297/

相关文章:

javascript - jquery rain datepicker firefox CSS 不工作

javascript - Webpack 如何使用 $translatePartialLoader 缓存 bust angular-translate?

javascript - 过滤对象数组,其中对象中的一个字段是数组

javascript - 插入 react native 的 typescript

javascript - 为什么 TypeScript 将每个数字视为自己的类型?

Angular - 与 react 形式的子组件交互

javascript - 更改 Redux 中的存储

javascript - Canvas 绘图工具

css - Angular 2动态添加样式到主机

html - Angular - 无法连接 HTML 页面中的值