我正在尝试使用异步验证创建一个控件,但我不想要同步验证:
使用 formBuilder 创建表单。
this.myForm = this.fb.group({
someControl: new FormControl(
"",
null,
[this.valueUnique.bind(this)]
)})
如果我将同步验证参数保持为 Validators.required 则不会出错。
错误:
ERROR 错误:期望验证器返回 Promise 或 Observable。在 toObservable (forms.js:603) 在 Array.map () 在 FormControl.asyncValidator (forms.js:591) 在 FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runAsyncValidator ( forms.js:2535) 在 FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2508) 在 FormControl.push../node_modules/@angular/forms/ fesm5/forms.js.AbstractControl._updateTreeValidity (forms.js:2523) at forms.js:2522 at forms.js:3309 at Array.forEach () at FormGroup.push../node_modules/@angular/forms/fesm5/ forms.js.FormGroup._forEachChild (forms.js:3309)
验证器功能:
/**
* Validator to checking existance/uniqueness
* of entered value
* @param control
*/
valueIsUnique(control: AbstractControl): Promise<ValidationErrors|null> | null {
if (control && (control.value !== null && control.value !== undefined)) {
return new Promise((resolve, reject) => {
this.service.checkValueExists(control.value).subscribe(res => {
{
if (res && res['data']) {
resolve({
unique: true
});
}
else {
resolve(null);
}
}
},
err=>
{
resolve(null);
});
});
}
}