首页 > 解决方案 > 无法读取未定义的属性成功

问题描述

ERROR TypeError: Cannot read property 'success' of undefined
    at Object.eval [as updateRenderer] HomeComponent.html:1

console.log(userDetail); 得到这个https://i.imgur.com/HNZ5PRg.png

该应用程序编译成功,并且在 Home Component HTML 中它正确打印了 first_name 但控制台仍然显示我上面提到的错误。

HTML 文件

<div *ngIf="isLoggedIn">
{{userDetail.success.first_name}}
</div>

打字稿文件

ngOnInit() {
    this.chk.checkLogin();
    this.chk.isUserLoggedIn.subscribe( (val) => {
      if(val) {
      this.isLoggedIn=val;
      }
    })

     //get user profile
     this.chk.getUserProfile().subscribe((res: any)=> {
      this.userDetail = res;
      console.log(this.userDetail);
      });

身份验证服务文件

   //Get User Profile
   getUserProfile() {
    return this.http.post(this.userProfileApi, null);
  }

标签: angular

解决方案


当您从异步请求中获取配置文件时,将抛出错误,因为数据不可用,您可以使用safe navigation operator(?) 处理它,如下所示

<h2 *ngIf="isLoggedIn">
  {{userDetail?.success?.first_name}}
</h2>

推荐阅读