【问题标题】:Angular 2+ Binding - WebAPI - Cannot read property 'Username' of undefinedAngular 2+ Binding - WebAPI - 无法读取未定义的属性“用户名”
【发布时间】:2019-03-07 11:23:02
【问题描述】:

我正在尝试在我的 Angular 应用程序中进行绑定。

在我的 component.html 上我有:

<span>{{this.test.Username}}</span>

这是我的 component.ts:

export class NavbarComponent implements AfterViewChecked, OnInit{     

   test: User;

   constructor(private userService: UserService) {                                                 
   }   

   ngOnInit() {
      var currentUser = JSON.parse(localStorage.getItem('currentUser'));
      var id = currentUser.userID;        
      this.userService.getById(id).subscribe(user => {                        
        this.test = new User();
        this.test = user;            
      });                 
   }
}

实际上,绑定有效并且用户名出现在客户端, 但问题是浏览器返回此错误:

ERROR TypeError: Cannot read property 'Username' of undefined
at Object.eval [as updateRenderer] (NavbarComponent.html:79)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:11087)
at checkAndUpdateView (core.js:10463)
at callViewAction (core.js:10699)
at execComponentViewsAction (core.js:10641)
at checkAndUpdateView (core.js:10464)
at callViewAction (core.js:10699)
at execComponentViewsAction (core.js:10641)
at checkAndUpdateView (core.js:10464)
at callViewAction (core.js:10699)

有人可以帮我吗?

提前致谢

【问题讨论】:

    标签: angular asp.net-web-api binding undefined typeerror


    【解决方案1】:

    将初始值设置为test

    test: User = { Username : null };
    

    或者在模板中使用可选操作符

    <span>{{this.test?.Username}}</span>
    

    【讨论】:

      【解决方案2】:

      如果User是一个类,则在constructor中初始化

       this.test = new User();
      

      【讨论】:

        猜你喜欢
        • 2018-09-26
        • 1970-01-01
        • 2021-11-04
        • 2018-12-18
        • 1970-01-01
        • 2018-04-15
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多