我正在创建一个自定义验证器,以验证来自后端api调用的电子邮件。 当寄存器组件加载时,已经多次调用了api,这在控制台中可以看到。我只希望在提交时将其命名。
公共服务
validateEmail(email: string) {
this.newHttp = new HttpClient(this.handler);
return this.newHttp.get(this.isVerifiedApi+'/'+email);
}
Validator
import { AbstractControl } from '@angular/forms';
import { PublicService } from '../services/public.service';
export class CheckEmail {
static createValidator(publicService: PublicService) {
return (control: AbstractControl) => {
return publicService.isVerified(control.value).subscribe((res: any)=>{
console.log(res);
console.log(res);
return 'validEmail';
},(err: any)=>{
console.log(err);
return 'null';
});
};
}
}
注册html组件
<div *ngIf="submitted && registerForm.controls.email.hasError('validEmail')" data-tip="Email is not valid"></div>
<input (focus)="emailExistsHide()" [ngClass]="{'face error-border': registerForm.get('email').invalid && registerForm.get('email').touched || registerForm.get('email').invalid && registerForm.get('email').invalid && submitted }" type="text" (focus)="focusEmailInput()" formControlName="email" name="email" placeholder="Email *" tabindex="3"/>
注册组件ts
this.registerForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email, CheckEmail.createValidator(this.publicService)]],
....
....
onSubmit() {
this.loading = true;
this.submitted = true;
...............
答案 0 :(得分:0)
如果这是个好方法,您可以进行重点关注
youFocusOutFunction()
{
console.log('Focus out fired');
// this.newHttp = new HttpClient(this.handler);
// return this.newHttp.get(this.isVerifiedApi+'/'+email);
}
yourFocusFunction()
{
console.log('Focus fired');
}
或者可以完成
doEmailValidation() {
var promise = new Promise((resolve, reject) => {
console.log("email validation")
// this.newHttp = new HttpClient(this.handler);
// return this.newHttp.get(this.isVerifiedApi+'/'+email);
});
return promise;
}
submit()
{
this.doEmailValidation().then(() =>
//do your submit task
console.log("submit task!"));
}