javascript - 无法读取未定义的属性 'first_name'
我有这个问题
无法读取未定义的属性 '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;
})
})这是错误的图片
答案#1
看起来您正在异步加载 newOrder。因此您的页面已被渲染,但异步任务尚未完成。
你写道,你在构造函数中声明了 this.newOrder.billing={}。因此,他现在在你的 HTML 中尝试读取 newOrder.billing.first_name。newOrder.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 | async }} 。async 管道还会确保 Angular 可以处理它。结合 [ngModel] 使用时,我认为 async 管道可能不起作用。但值得一试。
此致敬礼
答案#2
只要加一个引号,我觉得会有帮助。
<ion-input type="text" [(ngModel)]="newOrder?.billing.first_name"></ion-input>
