Angular 7:自定义异步验证器

问题描述 投票:0回答:1

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

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

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调用正在完成并正确返回,但电子邮件的表单控制仍处于待定状态。关于我做错了什么的任何想法?

angular validation asynchronous rxjs angular7
1个回答
0
投票

经过一段时间和更多研究后想出来。

验证类:

@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返回一个observable。

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

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

我在模块中添加了UniqueEmailValidator作为提供程序,并在此组件构造函数中注入。

© www.soinside.com 2019 - 2024. All rights reserved.