简体   繁体   中英

Observable add delay - Angular 2

I'm implementing a signup page. I want to check whether username already exists. I'm trying to implement asyncvalidator but it calls server everytime user enters a character, can you help in below code to add some delay so it only calls server with username when user stopped typing for some time? I read some observable debounceTime but couldn't get it working.

usernameAsyncValidator(control: FormControl): Observable<any> {
  return new Observable((obs: any) => {
    return this.http.get('http://localhost:3000/exists?name='+control.value)
      .debounceTime(400)                       <<-----------THIS IS NOT WORKING
      .distinctUntilChanged()                  <<-----------THIS IS NOT WORKING
      .subscribe(
        data => {
          if (data.status === 200) {
            obs.next({'userNameTaken': true});
          } else {
            obs.next(null);
          }
          obs.complete();
        },
        () => {
          obs.next(null);
          obs.complete();
        });
  });
}

Please let me know if I can explain better.

-Thanks

You're putting the debounceTime on the wrong observable. Currently it is sending the HTTP request then debouncing the response by 400ms (which doesn't really do anything). What you really want is to have a valueChanged observable on the field itself with a debounceTime which then calls to the API during that subscribe. Without seeing your other code it's hard to know exactly where to put it, but something like:

this.myForm.find("userName") //<-- returns your FormControl of interest
        .valueChanges //<-- Observable of whenever the value of that control changes
        .debounceTime(500) //<-- won't send updates until no more events have fired for however many ms
        .filter((value: string) => value != null && value.length > 0)
        .subscribe((value: string) => this.checkUserName(value)); //<-- call to your username API here

Hopefully this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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