Angular2 Custom Form Validators losing access to `this` in class

青春壹個敷衍的年華 提交于 2020-06-22 13:30:11

问题


I'm building an Angular 2 application (2.0) and I've got a form that makes use of the ReactiveForms module. As such, I'm using validator functions on the input fields, including custom validators. This works fine.

My issue is that I am also trying to use a custom AsyncValidator on a form field. It seems straight forward enough, but I can never reference properties inside the class from within the AsyncValidator method.

The FormGroup and the FormControl properties for the form itself and the input field look like this in the component's class:

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

There's also a FormBuilder in the ngOnInit() function that attaches the form to the form property.

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

My issue is that in the AsyncValidator, I am unable to reference any of the services I've defined in the component's class - including this.css. Here's the validator:

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

No matter what I do, this.css in the userNameAsyncValidator() call is undefined.

(I realize that my validator doesn't actually do anything - I just want to be able to call my ClientSecurity service so that I can, eventually, call a remote HTTP webservice to get a response as to whether the userName being entered is valid and not already in use.)


回答1:


Your validator is not being called with your component as this. Notice that you are passing a loose reference to this.userNameAsyncValidator You can bind your validator without worrying about this conflicts because angular validation doesn't rely on this

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


来源:https://stackoverflow.com/questions/40347735/angular2-custom-form-validators-losing-access-to-this-in-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!