Currently, I am in the process of incorporating asynchronous custom validation into my project. Below is the structure of my validation class:
export class CustomValidators{
_auth_service;
constructor(auth_service:AuthService){
this._auth_service = auth_service;
}
usernameTaken(control: Control) {
console.log(this._auth_service);
let q = new Promise<ValidationResult>((resolve, reject) => {
this._auth_service.emailtaken('email='+control.value).subscribe(data=>{
var result = data.json().result;
console.log(result);
if(result===true){
resolve({"usernameTaken": data});
}else{
resolve(null);
}
});
});
return q;
}
}
Upon further examination, in my component:
this.customValidators = new CustomValidators(this._auth_service);
I then proceed to integrate it into the form control like this:
this.emailControl = new Control('',Validators.compose([Validators.required, Validators.pattern(ConfigService.EMAIL_REGEX)]),this.customValidators.usernameTaken);
In this implementation, I have attempted to inject a service into my validator. However, upon testing, I observed that the this._auth_service
property within my validator method returns undefined
, although it was properly initialized in the validator's constructor.
My intention is to avoid utilizing the validator as a directive, even though it simplifies the process of injecting services. Any ideas on what might be causing this issue?