无法读取未定义的 属性 'first_name'
Cannot read property 'first_name' of undefined
我有这个问题
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;
})
})
这是错误图片
只需添加一个引号,我认为它会有所帮助。
<ion-input type="text" [(ngModel)]="newOrder?.billing.first_name"></ion-input>
看来您正在异步加载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 }}
异步管道还将确保 Angular 可以处理那个。
结合 [ngModel] 我认为异步管道将无法工作。但也许值得一试。
热烈的问候
如
@海妖。
但是@JanRecker 提供了两个解决方案:
如果您在插值中使用异步管道,它将不起作用,因为这适用于 Observables rxjs
.
因此,添加引号确实是一个有用的选项。
我有这个问题
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;
})
})
这是错误图片
只需添加一个引号,我认为它会有所帮助。
<ion-input type="text" [(ngModel)]="newOrder?.billing.first_name"></ion-input>
看来您正在异步加载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 }}
异步管道还将确保 Angular 可以处理那个。
结合 [ngModel] 我认为异步管道将无法工作。但也许值得一试。
热烈的问候
如 @海妖。
但是@JanRecker 提供了两个解决方案:
如果您在插值中使用异步管道,它将不起作用,因为这适用于 Observables rxjs
.
因此,添加引号确实是一个有用的选项。