Angular自定义验证器.如何使用给定的承诺验证表单字段?



我需要使用返回Promise的方法验证表单字段。但是它永远不会返回错误,因为Promises是异步的。

这是验证器:

static email(usersService: UsersService): ValidatorFn {
return (control: AbstractControl):{ [key: string]: boolean | null } => {
const email = control.value;
if (email) {
usersService.validateUsername(email).then(
(result) => { return result.username ? {emailExists: true} : null }
)
} else {
return null;
}
}}
这是我的UsersService方法
validateUsername(username: string): Promise<{"username": string}> {
return this.httpClient.post('/users/username_validation', {"username": username}).pipe(
map((body: {"username": string}) => body),
).toPromise()}

我所需要做的就是像这样使用AsyncValidator:

validator.ts

import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidator, ValidationErrors } from '@angular/forms';
import { Observable} from 'rxjs';
import { UsersService } from "@app/users/users.service";

@Injectable({
providedIn: 'root'
})
export class EmailValidator implements AsyncValidator {
constructor( private usersService: UsersService ) { }
validate( control: AbstractControl): Promise<ValidationErrors> | Observable<ValidationErrors> {
const email = control.value;
if (email) {
return this.usersService.validateUsername(email).then(
(result) => { 
console.log(result)
return result.username ? {emailExists: true} : null 
}
)
} else {
return null;
}
}
}

我想你错过了返回对于你的承诺,这应该工作

if (email) {
return usersService.validateUsername(email).then( // here in this line
(result) => { return result.username ? {emailExists: true} : null }
)
}

可以重构为

return (control: AbstractControl):Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => 
{
const email = control.value;
return (email &&  usersService.validateUsername(email).then( 
(result) => { return result.username ? {emailExists: true} : null }
)) || null;
}

最新更新