从 angular 2 中的表单验证器方法访问 class 变量

Accessing class variables from form validator method in angular 2

我正在尝试构建一个带有自定义验证的模式驱动表单。 我想验证用户输入的密码是否满足要求(后者大写,后者小写和数字)。 问题是我不想特别是在方法中编写正则表达式,我想要一个集中所有正则表达式的不可避免的服务。 我能够将服务注入组件 class 但无法以任何方式访问验证器方法内的服务实例。

有人知道我怎样才能访问该服务吗?

谢谢。

这是我的代码:

export class SignUpComponent implements OnInit {
regexService:RegexService
  builder: FormBuilder
  signUpForm: FormGroup;
  email: FormControl;
  password: FormControl;
  passwordAgain: FormControl;


  matchedPassword (input: any) {
    if(!input.root || !input.root.controls)
    return null;

    if(input.root.controls.password.value===input.root.controls.passwordAgain.value)
      return null;
    else
      return { mismatchedPassword: true };
   }

   passwordAnswerRequirements(input: any){
     if(!input.root || !input.root.controls)
     return null;

     if(this.regexService.getRegex('password').test(input.value))
        return null;
      else
        return {notAcceptablePassword:true}
   }



  constructor(builder: FormBuilder,regexService:RegexService) {
    this.builder=builder;
    this.regexService=regexService;
  }

  ngOnInit(){
    this.email = new FormControl('', [
       Validators.required,
    ]);
     this.password = new FormControl('', [
        Validators.required,
        this.matchedPassword,
        this.passwordAnswerRequirements
     ]);
     this.passwordAgain=new FormControl('',[
        Validators.required,
        this.matchedPassword,
        this.passwordAnswerRequirements
     ]);
     this.signUpForm = this.builder.group({
       email: this.email,
       password: this.password,
       passwordAgain:this.passwordAgain
     });
  }

我的服务名称是 'RegexService',验证函数名称是 'passwordAnswerRequirements'

您不需要声明您的服务变量,它已经在构造函数中,您可以在 class 中将其用作 this.regexService,因此

export class SignUpComponent implements OnInit {
//regexService:RegexService  -- remove this line
  builder: FormBuilder
  signUpForm: FormGroup;
  email: FormControl;
  password: FormControl;
  passwordAgain: FormControl;



  constructor(builder: FormBuilder,private regexService:RegexService) {
    this.builder=builder;
   // this.regexService=regexService; -- you don't need this line
  }
....

我终于找到了解决方案。这不是最美观的解决方案,但它确实有效... 我在 'passwordAnswerRequirements' 方法周围添加了一个包装函数,从那里我能够获取服务实例并将其放入局部变量中。

  passwordAnswerRequirements() {
    let passwordRegexExp = this.regexService.getRegex('password');
    return (input: any) => {
      if (!input.root || !input.root.controls)
        return null;
      if (passwordRegexExp.test(input.value))
        return null;
      else
        return { notAcceptablePassword: true }
    };
  }