I have been attempting to implement a custom validator to validate if an email is already in use. After consulting the documentation and reading various articles, I have come up with the following code:
In my auth.service.ts file
checkEmail(email) {
const r$ = of(true);
const x$ = of(false);
return this.http.post<any>(`${config.apiUrl}/users/email`, email)
.pipe(
mergeMap(v =>
iif(
() => v,
r$,
x$
)
)
);
}
In my component
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', [
Validators.required,
Validators.email,
this.checkEmail.bind(this)
]]
});
}
checkEmail(control: AbstractControl) {
if (control.value) {
return this.authService.checkEmail({email: control.value}).toPromise()
.then(response => {
return response ? { forbiddenName: {value: control.value}} : null;
});
}
}
Despite my efforts, it seems that the checkEmail() function is not returning the correct data for the validator's validation. How can I rectify this issue?