【发布时间】:2020-03-19 04:36:05
【问题描述】:
我是 Angular 8 的新手,正在尝试创建自定义异步验证器。以下是我的代码:
在我的打字稿文件中,我正在创建如下所示的表单字段。我只使用异步验证器(没有同步验证器,因此将“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) -->
我面临两个问题:
- 它不等待服务的响应。不知何故,它总是从 phoneValidator(control: AbstractControl) 方法返回错误
- 错误消息未显示在屏幕上。 f.controls['Phone'].hasError("phoneValidator") 总是假的
【问题讨论】:
-
对于你想要制作的一般任何东西
aysnc await,你必须使用你的函数async validationFunction() { await this.data = this.serviceCall() } -
我认为您不应该订阅您的验证器。你应该只返回可观察的。像这样的东西:
return this.phoneValidatorServiceCall(control.value).pipe(...) -
感谢@GaurangDhorda 的回复。你能举个例子吗?
-
感谢@AndreiGătej 的回复。我只尝试了管道,但它不起作用。
-
stackblitz.com/edit/angular-5hwcff 这个 stackblitz 链接可以帮助你
标签: angular angular8 angular-observable