这个错误通常发生在使用 Angular 表单验证时,当自定义验证器函数没有返回 Promise 或 Observable 对象时会触发。
要解决此问题,请确保您的自定义验证器函数返回 Promise 或 Observable 对象。如果您的验证器仅需要同步检查,则可以简单地将它们包装在 Promise.resolve()
中,以便使其返回 Promise 对象。例如:
function myCustomValidator(control: AbstractControl): Promise<ValidationErrors | null> {
const value = control.value;
if (value === 'invalid') {
return Promise.resolve({ invalid: true });
} else {
return Promise.resolve(null);
}
}
如果您的验证器需要进行异步操作,则应该返回一个 Observable 对象,例如:
function myAsyncValidator(control: AbstractControl): Observable<ValidationErrors | null> {
const value = control.value;
return someAsyncOperation(value).pipe(
map(result => result ? null : { invalid: true })
);
}