Reputation: 1
validation of username using API call In Signon.Component.ts this is the custom validation i used for username
username : ['',[Validators.required,this.customvalidationService.userNameValidators]]});
CustomValidationService inject the service in CustomValidation service constructor
private userStatusservice:UserstatusService
{
}
Call the API in the userstatusservice.ts*
userNameValidators(control: AbstractControl): {[key:string]:any} | null{
this.userStatusservice.ValidateUsername(control.value).subscribe(
res => {
res.forEach(obj=>{
if(obj.username==control.value)
{
this.user=obj;
}
})
});
}
It showing an error Cannot read property 'userStatusservice' of undefined I used bind(this)
bind(this)
loginForm = this.fb.group({
username : ['',[Validators.required,this.customvalidationService.userNameValidators.bind(this)]]});
it showing "Cannot read property 'ValidateUsername' of undefined"(this.userStatusservice.ValidateUsername(control.value))
Upvotes: 0
Views: 415
Reputation: 700
Since you're binding the userNameValidators
's this
-reference to the component, it won't be able to resolve the userStatusservice
-instance, which resolves in the error message you're receiving.
Maybe you should bind to this.customvalidationService
instead, eg.:
loginForm = this.fb.group({
username : ['',[Validators.required,this.customvalidationService.userNameValidators.bind(this.customvalidationService)]]});
EDIT: Alternative to above!
Consider another alternative, having the userNameValidators
become a factory for a validator, and "close over the service dependency", eg.:
createUserNameValidators: () => {
return (control: AbstractControl) {
this.userStatusservice.ValidateUsername(control.value).subscribe(
res => {
res.forEach(obj => {
if (obj.username == control.value) {
this.user = obj;
}
});
});
}
};
and then binding it to the formControl by:
loginForm = this.fb.group({
username : ['',[Validators.required,this.customvalidationService.createUserNameValidators()]]});
Upvotes: 1