Angular 2+ 绑定 - WebAPI - 无法读取未定义的 属性 'Username'

Angular 2+ Binding - WebAPI - Cannot read property 'Username' of undefined

我正在尝试在我的 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;            
      });                 
   }
}

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

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)

有人可以帮助我吗?

提前致谢

设置初始值为test

test: User = { Username : null };

或在模板中使用可选运算符

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

如果User是class,初始化在constructor

 this.test = new User();