Angular 2 Form异步验证ajax调用每个按键

时间:2016-08-06 08:01:53

标签: angular angular2-forms

我正在使用角度2形式异步验证,一切正常但后来我意识到ajax调用是在输入字段内的每个键按下服务器,这对服务器不好,我尝试了很多东西,但没有任何作用。所以请帮我解决这个问题。

form: FormGroup;
username: FormControl;
password: FormControl;

constructor(private fb: FormBuilder, private http: Http) {
    this.username = new FormControl("", Validators.compose([
        Validators.required, 
        SignupValidators.CannotContainSpace]),
        this.usernameShouldBeUnique.bind(this));

    this.password = new FormControl("", Validators.compose([Validators.required]));

    this.form = fb.group({
        username: this.username,
        password: this.password
    });
}

异步验证方法:

usernameShouldBeUnique(formControl:FormControl) {

    return new Promise(resolve => {

        let params = new URLSearchParams();
        params.set('username', formControl.value);
        this.http.get('http://localhost:1667/api/users/signup/namecheck', { search: params })
                  .subscribe(data => resolve(null), 
                             error => resolve({ usernameShouldBeUnique: true })
                            );
    });
}

2 个答案:

答案 0 :(得分:0)

根据{{​​3}},您可以使用令人惊讶的setTimeoutclearTimeout来延迟您的请求:

private timeout;

usernameShouldBeUnique(formControl: FormControl) {
  MY_DELAY = 500;
  clearTimeout(this.timeout);
  return new Promise(resolve => {
    let params = new URLSearchParams();
    params.set('username', formControl.value);
    this.timeout = setTimeout(() => {
      this.http.get('http://localhost:1667/api/users/signup/namecheck', {
          search: params
        })
        .subscribe(data => resolve(null),
          error => resolve({
            usernameShouldBeUnique: true
          })
        );
    }, MY_DELAY);
  });
}

MY_DELAY将导致请求等待500毫秒,以便在继续之前不再进行验证更改。

答案 1 :(得分:-1)

您可以使用名为 debounceTime或delay and distinctUntilchanged 的Rxjs运算符,如下所示,

usernameShouldBeUnique(formControl:FormControl) {



        let params = new URLSearchParams();
        params.set('username', formControl.value);

     return this.http.get('http://localhost:1667/api/users/signup/namecheck', { search: params })

     // .delay(300)                  <---- check this according to your need
        .debounceTime(300)         //<---- wait for 300ms pause in events
        .distinctUntilChanged()    //<---- ignore if next search term is same as previous


        .subscribe(data => resolve(null), 
                             error => resolve({ usernameShouldBeUnique: true })
                            );



}