xmaestro
xmaestro

Reputation: 1124

Angular 2 async custom validator

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?

Upvotes: 3

Views: 1049

Answers (1)

dfsq
dfsq

Reputation: 193301

Looks like you are losing a context. You should bind validator method to validator instance object explicitly:

this.emailControl = new Control('', Validators.compose([
  Validators.required, 
  Validators.pattern(ConfigService.EMAIL_REGEX)
 ]), this.customValidators.usernameTaken.bind(this.customValidators));

Upvotes: 7

Related Questions