gpt4 book ai didi

Angular 8 - 不可分配给 AsyncValidatorFn

转载 作者:行者123 更新时间:2023-12-05 02:10:18 24 4
gpt4 key购买 nike

我正在尝试以 react 形式创建自定义验证器函数。代码:

表单.component.ts

...
form = new FormGroup({
username: new FormControl('', [
Validators.required,
Validators.minLength(3)
],
UsernameService.isUnique
)
});
...

用户名.service.ts

...
static isUnique(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ notUnique: true });
}, 2000);
});
}
...

悬停在 UsernameService.isUnique 上时显示错误 -

"Argument type (control: AbstractControl) => Promise< ValidationErrors | null > is not assignable to parameter type AsyncValidatorFn | AsyncValidatorFn[] | null"

为什么会出现这个错误?根据文档 (https://angular.io/api/forms/AsyncValidatorFn),我使用了 AsyncValidatorFn 的正确调用签名。

最佳答案

解决方法其实很简单——

"UsernameService.isUnique"后面添加"as AsyncValidatorFn":

      UsernameService.isUnique as AsyncValidatorFn

或在“<>”中在其前面添加AsyncValidatorFn:

      <AsyncValidatorFn>UsernameService.isUnique

当然需要导入AsyncValidatorFn:

      import { AsyncValidatorFn } from '@angular/forms';

实践中的例子:

下图显示有错误WITHOUT "as AsyncValidatorFn":

enter image description here

错误信息大致相同:

      Argument of type '(control: FormControl) => 
Promise<any> | Observable<any>' is not assignable to
parameter of type 'AsyncValidatorFn | AsyncValidatorFn[]'

下面说明添加"as AsyncValidatorFn"后(后面)报错DISAPPEARED:

enter image description here

或(之前):

enter image description here

以下是“forbiddenEmails”函数:

enter image description here

其实很多类似的问题都可以用同样的方法解决。

关于Angular 8 - 不可分配给 AsyncValidatorFn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com