无法读取未定义的属性成功

时间:2019-02-19 10:14:31

标签: angular

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);
      });

AuthService文件

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

2 个答案:

答案 0 :(得分:2)

从异步请求中获取配置文件时,由于数据不可用,将引发错误,您可以使用 safe navigation operator (?)进行处理,如下所示< / p>

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

答案 1 :(得分:0)

请添加安全的操作员,例如{{userDetail?.success?.first_name}}。应该可以解决