简体   繁体   English

可观察到的添加延迟-角度2

[英]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? 我正在尝试实现asyncvalidator,但每次用户输入字符时它都会调用服务器,您能否在下面的代码中添加一些延迟,以便仅在用户停止输入一段时间后才使用用户名调用服务器? I read some observable debounceTime but couldn't get it working. 我读了一些可观察到的debounceTime,但无法正常工作。

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. 您正在将debounceTime放在错误的可观察范围内。 Currently it is sending the HTTP request then debouncing the response by 400ms (which doesn't really do anything). 当前,它正在发送HTTP请求,然后将响应消抖400ms(这实际上并没有执行任何操作)。 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. 您真正想要的是在字段本身上具有一个debounceTime可观察到的valueChanged,然后在该订阅期间调用该API。 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. 希望这会有所帮助。

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

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