无法读取未定义的属性“用户" [英] Cannot read property 'user' of undefined

查看:88
本文介绍了无法读取未定义的属性“用户"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从响应中读取数据并将其设置在HTML中,但这给了我未定义的错误.任何人都可以帮我在这里做错什么.

I am trying to read data from response and set it in my HTML.But it is giving me undefined error. Can anyone help what am I doing wrong here.

以下是该组件的摘录:

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>

推荐答案

使用安全运算符

<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>

这篇关于无法读取未定义的属性“用户"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆