我有从服务器绑定的异步数据的表单:
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>
只有当我将*ngIf="currentService.user"
添加到表单时,它才有效,但我希望在从服务器获取数据之前,渲染输入没有值。但我得到错误:
'无法读取未定义'的'属性'用户名'
我怎么解决这个问题?可能,我需要类似于异步管道到ngModel的东西,但显然这不起作用。
你可以尝试一下
<input [(ngModel)]="currentService.user && currentService.user.username">
<input [(ngModel)]="currentService.user && currentService.user.email">
您需要在服务中初始化用户。我认为你的代码看起来像这样:
private user: User;
然后你做一个HTTP调用或类似的东西来设置用户。但是在检索用户时,用户是未定义的,直到异步调用结束。
所以,如果你改变你的行,它应该工作:
private user: User = new User;
您必须将currentService
定义为下面的对象,然后您可以在从服务器获取数据之前使用它。
currentService = {
user : {
username: '',
email: ''
}
}
然后
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>