import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidatorFn, FormBuilder, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
import { UserCreateComponent } from 'src/app/components/users/user-create/user-create.component';
import { url } from 'src/app/config/config';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { resolve } from 'url';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
/**
* Class for async validations communicating with the REST-API.
*/
export class MailValidator {
static EmailUpdateValidator(UserCreateComponent: UserCreateComponent): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => {
let email = UserCreateComponent.gradientForm.get('email').value;
if (email == null) {
return null;
}
let id = UserCreateComponent.id;
return UserCreateComponent.http.get<any[]>(url + 'usuarios/emailInUse?email=' + UserCreateComponent.gradientForm.get('email').value)
.pipe(
map((resp: any) => {
let respuesta = null;
if (resp == null) {
return respuesta = null;
} else {
if (resp.user == null) {
return respuesta = null;
} else {
if ((email.localeCompare(resp.user.email) == 0)) {
if (id == resp.user.id) {
return respuesta = null;
} else {
return respuesta = { email_in_use: true };
}
} else {
return respuesta = null;
}
}
}
return respuesta;
})
)
};
}
}
I can solve this problem create a new validator
In component
this.gradientForm = this.fb.group({
id: [value.id],
name: [value.name, Validators.required],
surname: [value.surname, Validators.required],
email: [value.email, [Validators.required, Validators.email ],[MailValidator.EmailUpdateValidator(this)] ],
user: [value.user, Validators.required],
password: [value.password, Validators.required]
});
Please if my code can(could) be better ,let me know.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…