简体   繁体   中英

Form asynchronous validation in angular2

Am new to angular2 and i would like to validate an email address from the server but it fails

This is my form

this.userform = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this)]],
});

Then the _ValidationService i have The validation service is a service with @Injector

  @Injectable()
   export class ValidationService{

  constructor(
private _authService:AuthService
  ){}

 emailExistsValidator(control) {
   if (control.value != undefined) {
    return this._authService.checkExists("email")
      .map(response => {
       if (!response) {
          return {'emailNotExists': true};
        }
      });
     }
  }
}

And in the authservice i have (which is another service performing the http requests)

@Injectable()
 export class AuthService {

checkExists(value):Observable<any>{
return this._http.get(this.authurl+value)
  .map(response => {
   return response  //this is either true or false
  });
 }

}

I have followed This link in setting up my form but it fails

The error returned is

Cannot read property 'checkExists' of undefined
at UsersComponent.webpackJsonp.187.
 ValidationService.emailExistsValidator

What could be wrong

If this should point to the ValidationService , bind() needs to be

this.userform = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this._validationService)]],
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM