【问题标题】:Cannot read property 'user' of undefined [duplicate]无法读取未定义的属性“用户”[重复]
【发布时间】:2017-06-13 10:51:07
【问题描述】:

我正在尝试从响应中读取数据并将其设置在我的 HTML 中。但它给了我未定义的错误。谁能帮助我在这里做错了什么。

以下是组件的sn-p:

userProfile: any
constructor(private _userProfileService: UserProfileService ){}

ngOnInit(){
this._userProfileService.getProfileData()
.subscribe(data => {
    console.log("Response");
    console.log(data);
            this.userProfile = data;
            console.log(this.userProfile.user.firstname);
        });

}

HTML:

<h2>{{userProfile.user.firstname}} {{userProfile.user.lastname}}'s Profile <a href="#"><img src="assets/img/pen.png" alt="pen"></a></h2>

【问题讨论】:

  • 修复了这一行:userProfile: any = {};
  • 只有一个问题,你为什么不接受我的回答,因为它是第一个?
  • @VivekDoshi 首先感谢您的回答,它解决了我的问题。我没有检查谁在几毫秒发布了答案,据我了解,这个社区是为了帮助开发人员解决不为小事争吵。

标签: angular


【解决方案1】:

问题:

因为您试图在视图可用之前显示数据。

试试这个:

<div *ngIf='userProfile?.user'>
<h2>{{userProfile.user.firstname}} {{userProfile.user.lastname}}'s Profile <a href="#"><img src="assets/img/pen.png" alt="pen"></a></h2>
</div>

【讨论】:

    【解决方案2】:

    使用安全运算符

    <div *ngIf='userProfile?.user'>
    <h2>{{userProfile.user.firstname}} {{userProfile.user.lastname}}'s Profile <a href="#"><img src="assets/img/pen.png" alt="pen"></a></h2>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2019-03-10
      • 2017-12-02
      • 2016-09-14
      • 2021-03-18
      • 2018-11-18
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多