【发布时间】:2020-06-29 16:27:48
【问题描述】:
我需要在向数据库发送请求后创建一个表单并从服务器获取响应并用该数据填写表单。
我为发送请求编写此代码并从该响应中填写表单:
data: any;
accountSettingFG: FormGroup;
constructor(private formBuilder: FormBuilder, private accountsettingService: AccountSettingService) {
}
ngOnInit(): void {
this.FetchData().then(res=>{
this.InitialForm();
});
}
InitialForm(): void {
this.accountSettingFG = this.formBuilder.group({
twoFactorAuthentication: [this.data.twoFactorAuthentication],
email: [this.data.email],
sms: [this.data.sms]
})
}
FetchData() {
let promiss = new Promise((resolve, reject) => {
this.accountsettingService.GetListItem('/SiteOption/AccountSecurity')
.toPromise()
.then(res => {
this.data= res.result['accountSecuritySettingsModel']
resolve();
}, msg => {
reject(msg);
})
})
return promiss;
}
这是我的Html Code :
<form
class="form"
id="postform"
[formGroup]="accountSettingFG"
(ngSubmit)="onSubmit()"
autocomplete="off"
>
<mat-slide-toggle color="primary" formControlName="twoFactorAuthentication">
{{ "SETTING.ACCOUNT_SCURITY.TOW_FACTOR_ACUTHENTICATION" | translate }}
</mat-slide-toggle>
<mat-slide-toggle color="primary" formControlName="email">
{{ "SETTING.ACCOUNT_SCURITY.EMAIL" | translate }}
</mat-slide-toggle>
<mat-slide-toggle color="primary" formControlName="sms">
{{ "SETTING.ACCOUNT_SCURITY.SMS" | translate }}
</mat-slide-toggle>
</form>
但是当我运行项目时,它会显示这个错误:
错误错误:formGroup 需要一个 FormGroup 实例。请传一个。
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
at Function.missingFormException (forms.js:2283)
at FormGroupDirective._checkFormPresent (forms.js:7490)
at FormGroupDirective.ngOnChanges (forms.js:7280)
at checkAndUpdateDirectiveInline (core.js:33257)
at checkAndUpdateNodeInline (core.js:46077)
at checkAndUpdateNode (core.js:46016)
at debugCheckAndUpdateNode (core.js:47039)
at debugCheckDirectivesFn (core.js:46982)
at Object.updateDirectives (account-option.component.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:46970)
有什么问题吗?我该如何解决这个问题?
【问题讨论】:
-
在初始渲染中,表单组将不会被创建,因为请求仍处于未决状态且未解决。因此,
this.accountSettingFG未设置并导致看到的错误。一种解决方案是在数据解析之前根本不显示此组件。 -
@BenjaminEckardt 我该怎么做?我无法在路由中使用 reolve
标签: javascript angular typescript