【问题标题】:Angular 2 async custom validatorAngular 2 异步自定义验证器
【发布时间】:2016-04-20 09:56:21
【问题描述】:

我正在尝试实现异步自定义验证,并且我的验证类如下

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 属性出现在我的验证器方法中undefined。它似乎在我的验证器构造函数中填充得很好。

我不想使用验证器作为指令,我理解这使得注入服务变得容易。

可能是什么问题?

【问题讨论】:

  • this._auth_service 在构造函数中有值吗?
  • 确实如此。但在验证器方法中,它显示为undefined
  • 它是undefined,因为this 不是CustomValidators 的实例。
  • @dfsq 所以在使用bind() 之前,我的验证器是被静态调用的并且可以理解地脱离上下文,并且使用bind 使得该函数被调用为验证器类的方法?
  • 有点。如果您要这样做,这也是一样的:var user = {name: 'Thomas', getName: function() { return this.name }}; var getName = user.getName; getName()。方法与基础对象分离,上下文丢失。但是,var getName = user.getName.bind(user) 绑定到上下文并始终正确执行。

标签: typescript angular


【解决方案1】:

看起来您正在丢失上下文。您应该将验证器方法显式绑定到验证器实例对象:

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

【讨论】:

  • 您能否详细说明.bind() 在这种情况下的作用?
  • it should be noted(因为问题被标记为 TS)
  • Function.prototype.bind 返回一个新函数,该函数将在适当的上下文中调用 this.customValidators.usernameTaken。这很重要,因为this.customValidators.usernameTaken 只是对具有动态上下文的验证器方法的引用,这意味着其中的this 取决于该方法的调用方式,但this 将不再是this.customValidators
  • 有趣。谢谢!
  • @drewmoore 绑定是无害的,它是非常有用且强大的上下文执行控制方法。当然应该明智地使用它,但它返回any 的事实并不总是一个问题(就像在这种情况下它根本不是问题)。同时,使用箭头函数来完成绑定的操作,看起来很奇怪。但当然也有可能:() =&gt; this.customValidators.usernameTaken().
猜你喜欢
  • 1970-01-01
  • 2020-03-06
  • 2023-03-12
  • 1970-01-01
  • 2019-03-12
  • 2018-01-26
  • 2021-01-12
  • 2017-11-30
  • 2019-11-09
相关资源
最近更新 更多