加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:01:33 所属栏目:安全 来源:网络整理
导读:我正在尝试实现异步自定义验证,我有如下的验证类 export class CustomValidators{_auth_service;constructor(auth_service:AuthService){ this._auth_service = auth_service;}usernameTaken(control: Control) { console.log(this._auth_service); let q =
我正在尝试实现异步自定义验证,我有如下的验证类

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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读