ngModel 中的异步数据
Async data in ngModel
我有带有异步数据的表单:
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>
仅当我将 *ngIf="currentService.user"
添加到表单时它才有效,但我想在从服务器获取数据之前呈现没有值的输入。但是我收到以下错误:
'Cannot read property 'username' of undefined'
我该如何解决这个问题?可能,我需要 async
管道到 ngModel
之类的东西,但这显然不起作用。
您需要在您的服务中初始化用户。我认为您的代码如下所示:
private user: User;
然后您进行 HTTP 调用或类似的设置用户。
但是在检索用户时,在异步调用完成之前,用户是未定义的。
因此,如果您像这样更改行,它应该可以工作:
private user: User = new User;
你可以试试这个
<input [(ngModel)]="currentService.user && currentService.user.username">
<input [(ngModel)]="currentService.user && currentService.user.email">
Working Example
您必须将 currentService
定义为如下对象,然后您才能在从服务器获取数据之前使用它。
currentService = {
user : {
username: '',
email: ''
}
}
然后
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>
我有带有异步数据的表单:
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>
仅当我将 *ngIf="currentService.user"
添加到表单时它才有效,但我想在从服务器获取数据之前呈现没有值的输入。但是我收到以下错误:
'Cannot read property 'username' of undefined'
我该如何解决这个问题?可能,我需要 async
管道到 ngModel
之类的东西,但这显然不起作用。
您需要在您的服务中初始化用户。我认为您的代码如下所示:
private user: User;
然后您进行 HTTP 调用或类似的设置用户。 但是在检索用户时,在异步调用完成之前,用户是未定义的。
因此,如果您像这样更改行,它应该可以工作:
private user: User = new User;
你可以试试这个
<input [(ngModel)]="currentService.user && currentService.user.username">
<input [(ngModel)]="currentService.user && currentService.user.email">
Working Example
您必须将 currentService
定义为如下对象,然后您才能在从服务器获取数据之前使用它。
currentService = {
user : {
username: '',
email: ''
}
}
然后
<form>
<input [(ngModel)]="currentService.user.username">
<input [(ngModel)]="currentService.user.email">
</form>