Angular 7 : Custom Async Validator

标签 angular validation asynchronous rxjs angular7

我正在尝试为我的注册表单创建一个自定义异步验证器,它会检查电子邮件是否已存在。如果电子邮件不存在,后端返回 404;如果存在,则返回 200(无法更改此旧代码)。

我找到了一些教程,但没有找到使用最新 rxjs 库的教程。我创建了这个验证类:

export class UniqueEmailValidator {
    static createValidator(httpClient: HttpClient, degree: number, wlId: number) {
        return (control: AbstractControl) => {
            return httpClient.get(`${url}?degree=${degree}&email=${control.value}&wl_id=${wlId}`)
                .pipe(
                    map(
                        (response: Response) => {
                            return response.status === 404 ? null : { emailNotUnique: true };
                        }
                    )
                );
        };
    }
}

并在我的 ts 文件中创建我正在使用的表单

this.registerForm = this.fb.group({
            email: ['', [Validators.required, Validators.email], UniqueEmailValidator.createValidator(
                this.httpClient, this.wlService.wl.degree, this.wlService.wl.id)],

xhr 调用正在完成并正确返回,但电子邮件的表单控件仍处于待处理状态。关于我做错了什么有什么想法吗?

最佳答案

经过一段时间和更多研究后弄清楚了。

验证类:

@Injectable()
export class UniqueEmailValidator {
    constructor(private http: HttpClient) {}

    searchEmail(email: string, degree: number, wlId: number) {
        return timer(1000)
            .pipe(
                switchMap(() => {
                    // Check if email is unique
                    return this.http.get<any>(`${url}?degree=${degree}&email=${email}&wl_id=${wlId}`);
                })
            );
    }

    createValidator(degree: number, wlId: number): AsyncValidatorFn {
        return (control: AbstractControl): Observable<{ [key: string]: any } | null> => {
            return this.searchEmail(control.value, degree, wlId)
                .pipe(
                    map(
                        (response: Response) => {
                            return null;
                        },
                    ),
                    catchError(
                        (err: any) => {
                            return err.status === 404 ? of(null) : of({ emailNotUnique: true });
                        },
                    ),
                );
        };
    }
}

不确定计时器是否可以更改,但我在一篇文章中找到了它,它工作正常。希望得到一些确认。

基本上,我正在执行 catchError,因为后端的响应返回 404,并从 catchError 再次返回可观察值。

然后在我正在做的表单创建中:

        this.registerForm = this.fb.group({
            email: ['', [Validators.required, Validators.email], this.uniqueEmailValidator.createValidator(
            this.wlService.wl.degree, this.wlService.wl.id
        )],

我将 UniqueEmailValidator 添加为模块中的提供程序,并注入(inject)到此组件构造函数中。

关于 Angular 7 : Custom Async Validator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279113/

相关文章:

java - 更好地处理android中的数字格式异常

具有异步方法调用的 Java 服务

json - 如何在嵌套的 json 对象上执行 ngFor 循环?

c# - 除了需要为我的测试方法工作外,没有其他验证

javascript - d3.js v5.9.1 - 此版本中的某些方法未按预期工作

iphone - 解释 Core Data 验证消息并将其显示在 iPhone 上的好模式是什么?

javascript - 异步 Lambda 函数 : Returning promise or sending responseURL does not terminate CloudFormation custom resource invocation

asynchronous - 始终返回 Ok HttpResponse 然后在 actix-web 处理程序中工作

javascript - 总值包含 Highcharts 中当前值的一部分

angular - 未知元素 - Angular 2 与 Angular 2 Material