【发布时间】: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