【问题标题】:Form asynchronous validation in angular2在angular2中形成异步验证
【发布时间】:2017-01-29 22:46:06
【问题描述】:

我是 angular2 新手,我想验证来自服务器的电子邮件地址,但它失败了

这是我的表格

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

然后我有 _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};
        }
      });
     }
  }
}

在我拥有的 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
  });
 }

}

我已按照This link 设置我的表单,但它失败了

返回的错误是

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

可能有什么问题

【问题讨论】:

  • 您需要为您的代码提供更多上下文。 emailExistsValidator() 方法在哪里? this._authService 是如何实例化的?
  • 对不起,我更新了问题所有这些都是不同的服务,this._authservice 在构造函数中被实例化

标签: javascript angular typescript


【解决方案1】:

如果this应该指向ValidationServicebind()需要是

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

【讨论】:

  • 现在出现另一个问题,我想仅在用户完成输入电子邮件后验证,目前在每个按下的键上都有效,我该怎么做
  • 当您不希望用户看到它时,只需隐藏验证错误。喜欢showEmailValidation:boolean = false;&lt;input (blur)="showEmailValidation = true" ...&gt;
猜你喜欢
  • 2018-04-16
  • 2017-04-08
  • 2017-10-23
  • 2016-07-26
  • 2016-02-21
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2017-11-02
相关资源
最近更新 更多