[英]Angular 2+ Binding - WebAPI - Cannot read property 'Username' of undefined
我正在尝试在我的角度应用程序中进行绑定。
在我的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)
有人能帮我吗?
提前致谢
设置初始值进行test
test: User = { Username : null };
或在模板中使用可选的运算符
<span>{{this.test?.Username}}</span>
如果User
是一个类,则在constructor
函数中初始化
this.test = new User();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.