简体   繁体   English

在 angular2 中形成异步验证

[英]Form asynchronous validation in angular2

Am new to angular2 and i would like to validate an email address from the server but it fails我是 angular2 的新手,我想验证来自服务器的电子邮件地址,但它失败了

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然后我拥有的 _ValidationService 验证服务是一个带有@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)在 authservice 我有(这是另一个执行 http 请求的服务)

@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应该指向ValidationService ,则bind()需要是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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