gpt4 book ai didi

angular - 异步自定义验证器无法正常工作并在 Angular 8 中显示错误消息

转载 作者:行者123 更新时间:2023-12-04 14:17:19 25 4
gpt4 key购买 nike

我是 Angular 8 的新手,正在尝试创建自定义异步验证器。下面是我的代码:

在我的 typescript 文件中,我正在创建如下所示的表单字段。我只使用异步验证器(没有同步验证器,因此将“null”作为第二个参数传递):

group.addControl(control.Name, this.fb.control('', null, this.phoneValidator));

下面是我的异步验证器代码:

phoneValidator(control: AbstractControl) {
if(control.value == '' || control.value == undefined || control.value == null) {
return null;
}
else {
return this.phoneValidatorServiceCall(control.value)
//.pipe(map((data: any) => {
// return (data.Response == "True" ? null : { phoneValidator: true });
//}))
.subscribe(data => {
return (data.Response == "True" ? null : { phoneValidator: true });
})
}
}

在上面的代码中,我尝试使用“管道”,只是它不起作用,所以只使用了“订阅”,但即使这样也不起作用。以下是我的服务方式:

phoneValidatorServiceCall(input): Observable<any> {
return this.http.post<any>('http://xxxxxxxx:xxxx/validate/phone', { 'Text': input });
}

为了在 html 中显示错误,我使用以下代码:

<mat-form-field class="example-full-width">
<input #dyInput [formControlName]="Phone" matInput [placeholder]="Phone" [required]="IsRequiredField">

<!-- For showing validation message(s) (Start) -->
<mat-error *ngFor="let v of Config.Validators">
{{ f.controls['Phone'].invalid }} // comes true only on error
{{ f.controls['Phone'].hasError("phoneValidator") }} // always coming false even for wrong input
<strong *ngIf="f.controls['Phone'].invalid && f.controls['Phone'].hasError('phoneValidator')">
{{ My Message Here }}
</strong>
</mat-error>
<!-- For showing validation message(s) (End) -->

我面临两个问题:

  1. 它不是在等待服务的响应。不知何故,它总是从 phoneValidator(control: AbstractControl) 方法返回错误
  2. 错误消息未显示在屏幕上。 f.controls['Phone'].hasError("phoneValidator") 总是出错

最佳答案

您已获得有关如何解决问题的好建议。那些聚集...所以你当前的问题是:

添加验证器的返回类型:

Observable<ValidationErrors | null>

因为这就是您要返回的内容。

所以不要在验证器中订阅,而是返回可观察的。此外,您需要在有效时return of(null),因为再次……我们需要返回一个可观察对象。因此,将您的验证器修改为:

import { of } from 'rxjs';

//....

phoneValidator(control: AbstractControl): Observable<ValidationErrors | null> {
if (!control.value) {
return of(null);
} else {
return this.phoneValidatorServiceCall(control.value)
.pipe(map((data: any) => {
return (data.Response == "True" ? null : { phoneValidator: true });
}))
}
}

关于angular - 异步自定义验证器无法正常工作并在 Angular 8 中显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005521/

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