簡體   English   中英

Angular 7:自定義異步驗證器

[英]Angular 7: Custom Async Validator

我正在嘗試為我的注冊表單創建一個自定義異步驗證器,用於檢查是否已存在電子郵件。 如果電子郵件不存在,后端將返回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調用正在完成並正確返回,但電子郵件的表單控制仍處於待定狀態。 關於我做錯了什么的任何想法?

經過一段時間和更多研究后想出來。

驗證類:

@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作為提供程序,並在此組件構造函數中注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM