首页 文章

Angular2自定义表单验证器在类中失去对“this”的访问权限

提问于
浏览
10

我'm building an Angular 2 application (2.0) and I'有一个使用 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 Web服务来获得关于输入的userName是否有效的响应 . 尚未使用 . )

1 回答

  • 25

    您的验证程序未使用您的组件调用 this . 请注意,您正在传递一个松散的引用 this.userNameAsyncValidator 您可以绑定验证器而不必担心 this 冲突,因为角度验证不依赖于 this

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

相关问题