I'm trying to implement async custom validation and i have the validation class as below
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;
}
}
And in my component
this.customValidators = new CustomValidators(this._auth_service);
The i add it to form control like so
this.emailControl = new Control('',Validators.compose([Validators.required, Validators.pattern(ConfigService.EMAIL_REGEX)]),this.customValidators.usernameTaken);
You can see that i am trying to inject a service in my validator. And then to use the validator function in my component i had to create an object of the validator and use it's method. I have debugged to see that the this._auth_service property appear undefined in my validator method. It seems to be populated fine in my validator constructor.
I do not want to use the validator as directive which i understand makes injecting service easy.
What could be the problem?
this._auth_servicehave a value in the constructor?undefinedundefinedbecausethisis not an instance ofCustomValidators.bind(), my validator was being called statically and was understandably out of context, and usingbindmakes the function being called as method of validator class?var user = {name: 'Thomas', getName: function() { return this.name }}; var getName = user.getName; getName(). Method is detauched from the base object, context lost. However,var getName = user.getName.bind(user)is bound to context and always execute properly.