【问题标题】:Angular2 Custom Form Validators losing access to `this` in classAngular2 自定义表单验证器在类中无法访问“this”
【发布时间】:2016-10-31 17:53:48
【问题描述】:

我正在构建一个 Angular 2 应用程序 (2.0),并且我有一个使用 ReactiveForms 模块的表单。因此,我在输入字段上使用验证器函数,包括自定义验证器。这很好用。

我的问题是我也在尝试在表单字段上使用自定义 AsyncValidator。这似乎很简单,但我永远无法从 AsyncValidator 方法中引用类内的属性。

表单本身和输入字段的FormGroupFormControl 属性在组件的类中如下所示:

form: FormGroup;
userName = new FormControl("", [Validators.required], [this.userNameAsyncValidator]);

ngOnInit() 函数中还有一个FormBuilder 将表单附加到form 属性。

constructor(private fb: FormBuilder, // this.fb comes from here
          private css: ClientSecurityService) { // this.css comes from here
}

ngOnInit() {
  this.form = this.fb.group({
      "userName": this.userName
    }
  );
}

我的问题是在 AsyncValidator 中,我无法引用我在组件类中定义的任何服务 - 包括 this.css。这是验证器:

userNameAsyncValidator(control: FormControl): {[key: string]: any} {
  return new Promise(resolve => {
    this.css.getUrl()
      .subscribe(
        data => {
          console.log('Returned http data:', data);
          resolve(null);
        },
        err => {
          // Log errors if any
          console.log(err);
        });
  });
}

无论我做什么,userNameAsyncValidator() 调用中的this.css 都是未定义的。

(我意识到我的验证器实际上并没有做任何事情 - 我只是希望能够调用我的 ClientSecurity 服务,以便最终可以调用远程 HTTP 网络服务来获得关于是否输入用户名的响应有效且尚未使用。)

【问题讨论】:

  • 当您使用箭头函数时,问题可能是userNameAsyncValidator 函数未绑定到右侧this。谁调用了这个函数?这个函数是如何传递的?如果你通过它,然后像这样通过它:this.userNameAsyncValidator.bind(this)
  • @NitzanTomer 可能是类(原型)方法,不能用箭头函数定义

标签: validation angular typescript this


【解决方案1】:

您的验证器没有被您的组件调用为this。请注意,您传递的是对this.userNameAsyncValidator 的松散引用,您可以绑定验证器而不必担心this 冲突,因为角度验证不依赖于this

userName = new FormControl("", [
    Validators.required
], [
    this.userNameAsyncValidator.bind(this)
]);

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多