- 创建异步验证器服务:
- 首先创建一个新的服务,例如
EmailExistsValidatorService
。
- 在服务中注入
HttpClient
(假设使用HttpClient
进行后端请求)。
- 编写一个方法,该方法接收邮箱作为参数,并返回一个
Observable<boolean>
。例如:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class EmailExistsValidatorService {
constructor(private http: HttpClient) {}
checkEmailExists(email: string): Observable<boolean> {
const url = `your - backend - url/check - email - exists?email=${email}`;
return this.http.get(url).pipe(
map((response: any) => {
// 假设后端返回一个对象,根据返回数据判断邮箱是否存在
return response.exists;
})
);
}
}
- 创建异步验证器函数:
- 在组件或共享的验证器模块中创建异步验证器函数。
- 该函数接收
EmailExistsValidatorService
作为参数,并返回一个验证函数。
import { AbstractControl, ValidationErrors, AsyncValidatorFn } from '@angular/forms';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { EmailExistsValidatorService } from './email - exists - validator.service';
export function emailExistsValidator(emailExistsService: EmailExistsValidatorService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return emailExistsService.checkEmailExists(control.value).pipe(
map((exists: boolean) => {
return exists? { emailExists: true } : null;
})
);
};
}
- 应用异步验证器到表单输入控件:
- 在组件的
ngOnInit
方法或表单构建逻辑中,将异步验证器应用到邮箱输入控件。
- 假设使用
FormGroup
和FormControl
构建表单:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { EmailExistsValidatorService } from './email - exists - validator.service';
import { emailExistsValidator } from './email - exists - validator';
@Component({
selector: 'app - email - form',
templateUrl: './email - form.component.html',
styleUrls: ['./email - form.component.css']
})
export class EmailFormComponent {
emailForm: FormGroup;
constructor(private emailExistsService: EmailExistsValidatorService) {}
ngOnInit() {
this.emailForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email], [emailExistsValidator(this.emailExistsService)])
});
}
}
- 在模板中显示验证错误信息:
- 在HTML模板中,使用
*ngIf
指令来显示当邮箱已存在时的错误信息。
<form [formGroup]="emailForm">
<input type="email" formControlName="email">
<div *ngIf="emailForm.get('email').hasError('emailExists') && (emailForm.get('email').touched || emailForm.get('email').dirty)">
This email already exists.
</div>
</form>