我正在尝试在我的角度应用程序中进行绑定。
在我的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)
有人可以帮我吗?
预先感谢
答案 0 :(得分:1)
将初始值设置为test
test: User = { Username : null };
或在模板中使用可选的运算符
<span>{{this.test?.Username}}</span>
答案 1 :(得分:0)
如果User
是一个类,请在constructor
中初始化
this.test = new User();