gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:32 24 4
gpt4 key购买 nike

我有这个问题

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com