javascript - Angular2 中的表单异步验证

标签 javascript angular typescript

我是 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

可能出了什么问题

最佳答案

如果this应该指向ValidationService,则需要bind()

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

关于javascript - Angular2 中的表单异步验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41921768/

相关文章:

javascript - 如何使用jQuery为带有标题的图像链接创建搜索脚本

javascript - 同一字符串的两个不同部分的不同字体系列

javascript - Angular:用逗号格式化数字

typescript - ts.setSyntheticLeadingComments 不会删除现有评论

typescript - 有没有办法从 TypeORM 关系中排除字段(或包含某些字段)

angular - 错误 TS1192 : Module '" A. 模块“”没有默认导出

javascript - 比较运算符中数字和字符串的强制转换

javascript - SharePoint 2013 - 使用 jQuery 交换 CSS 文件

android - Ionic/Cordova 应用程序测试非常慢

javascript - 如何检测 Angular2 中 div 的中间点击?