typescript – Angular 2异步自定义验证器

前端之家收集整理的这篇文章主要介绍了typescript – Angular 2异步自定义验证器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试实现异步自定义验证,我有如下的验证类

export class CustomValidators{
_auth_service;
constructor(auth_service:AuthService){
    this._auth_service = auth_service;
}

usernaMetaken(control: Control) {
    console.log(this._auth_service);
    let q = new Promise<ValidationResult>((resolve,reject) => {
    this._auth_service.emailtaken('email='+control.value).subscribe(data=>{
            var result = data.json().result;
            console.log(result);
            if(result===true){
                resolve({"usernaMetaken": data});
            }else{
                resolve(null);
            }
        });
});
return q;
}

}

在我的组件中

this.customValidators = new CustomValidators(this._auth_service);

我将它添加到表单控件中

this.emailControl = new Control('',Validators.compose([Validators.required,Validators.pattern(ConfigService.EMAIL_REGEX)]),this.customValidators.usernaMetaken);

您可以看到我正在尝试在验证器中注入服务.然后在我的组件中使用验证器函数我必须创建验证器的对象并使用它的方法.我已经调试过,看到this._auth_service属性在我的验证器方法显示为未定义.它似乎在我的验证器构造函数中填充得很好.

我不想使用验证器作为指令,我明白使注入服务变得容易.

可能是什么问题呢?

解决方法

看起来你正在失去一个背景.您应该将validator方法显式绑定到验证器实例对象:

this.emailControl = new Control('',Validators.compose([
  Validators.required,Validators.pattern(ConfigService.EMAIL_REGEX)
 ]),this.customValidators.usernaMetaken.bind(this.customValidators));

猜你在找的Angularjs相关文章