简体   繁体   English

我怎样才能使角度异步验证器超时

[英]How can i make an angular async validator timeout

Firstly i have this async validator for angular for password validation and I'm trying to make a delay for the message in html but it doesnt seem to work, how do i need to call it to work.I checked via console.log(control) in the function and it returns the expected result but it still appears instantly on how i called it in HTML code. 首先,我有一个用于角度验证密码的异步验证器,我正在尝试延迟html中的消息,但它似乎不起作用,我需要如何调用它才能正常工作。我通过console.log( )在函数中,它返回预期的结果,但在我在HTML代码中如何调用它时,它仍然立即显示。

I will put sample code here. 我将在此处放置示例代码。 Here i make the form with the validators. 在这里,我与验证人一起填写表格。

constructor(fb: FormBuilder)
  {
    this.form = fb.group({
      password: ['', Validators.required,this.asyncValidator],
      confirmPassword: ['', Validators.required,this.asyncValidator]
    })
  }

Here is the validation function. 这是验证功能。

asyncValidator(control:FormControl):any{
    return new Promise(
      (resolve) =>{
        setTimeout(() => {
          if((control.password).length < 6 && (control.password).length > 1)
              console.log("true");
          console.log("false");
          resolve(null);
        },2000);
      }
    );
 }

Here is the HTML code that i use in the page to see the delayed message(that doesn't work). 这是我在页面中使用的HTML代码,用于查看延迟的消息(不起作用)。

<div class="alert alert-danger"
  *ngIf="asyncValidator(this.form.controls.password)">Password too short</div>

How do i need to use the async validator so my message in HTML appears with a 2 secs delay? 我该如何使用异步验证程序,以便我的HTML消息出现2秒的延迟?

You seem to have misunderstood what async validators do and how they're used and written. 您似乎误解了异步验证器的功能以及如何使用和编写它们。 Hence, there are a lot of issues with your implementation. 因此,您的实现存在很多问题。 Here's how you can fix them. 解决方法如下。

1. Get rid of the code in your constructor and move it to ngOnInit : 1.删​​除constructor中的代码,然后将其移至ngOnInit

ngOnInit() {
  this.form = this.fb.group({
    password: ['', [Validators.required], [this.asyncValidator.bind(this)]],
    confirmPassword: ['', [Validators.required], [this.asyncValidator.bind(this)]]
  });
}

Rationale: constructor s are supposed to be skinny according to Misko Hevery 基本原理: 根据 Misko Hevery的观点, constructor应该很瘦

Experienced developers agree that components should be cheap and safe to construct. 经验丰富的开发人员同意,组件应该便宜且安全地构造。

And, the async validators, are passed as the third argument to a FormControl 并且, async验证器将作为第三个参数传递给FormControl

Also, since the async validators are functions that are going to be called by Angular and not by us, we need to set the context of this explicitly by calling bind(this) on the async validator function. 此外,由于async验证是要通过角,而不是被称为由我们的功能,我们需要设置的背景下this明确地通过调用bind(this)在异步验证功能。

2. Now, the promise returned by the asyncValidator , should resolve to null in case of no error and an error object in case of an error: 2.现在,由asyncValidator返回的asyncValidator在没有错误的情况下应解析为null在发生错误的情况下应为错误对象:

asyncValidator(control: FormControl): any {
  return new Promise(
    (resolve) => {
      setTimeout(() => {
        if ((control.value).length < 6 && (control.value).length > 1)
          resolve(null);
        else
          resolve({
            shortPassword: true
          });
      }, 2000);
    }
  );
}

3. Create a function that is going to return a boolean based on whether a FormControl is touched and has an error that you're returning from your asyncValidator function: 3.创建一个函数,该函数将基于是否触摸了FormControl并从asyncValidator函数返回错误而返回asyncValidator值:

getFormControlError(controlName) {
  const control = this.form.get(controlName);
  return control.touched && control.errors && control.errors.shortPassword;
}

Rationale: This is something that we'll be using in our template. 原理:这是我们将在模板中使用的东西。

4. Update your template to show the error only if the input field is touched and has that error: 4.更新模板以仅在触摸输入字段并显示该错误时显示错误:

<form [formGroup]="form">
  Password: <input type="text" formControlName="password">
  <div class="alert alert-danger"
  *ngIf="getFormControlError('password')">Password too short</div>

  <br><br>

  Confirm Password: <input type="text" formControlName="confirmPassword"> 
  <div class="alert alert-danger"
  *ngIf="getFormControlError('confirmPassword')">Password too short</div>
  <br> 
  <br>
</form>

Here's a Working Sample Stackblitz for your ref. 这是供您参考的工作样本Stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM