可观察的添加延迟 - Angular 2

时间:2016-08-23 15:55:19

标签: javascript angular rxjs observable

我正在实施注册页面。我想检查用户名是否已经存在。我正在尝试实现asyncvalidator,但每次用户输入一个字符时都会调用服务器,你能帮助在下面的代码中添加一些延迟,这样当用户停止输入一段时间后它只会调用带有用户名的服务器吗?我读了一些可观察到的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();
        });
  });
}

如果我能更好地解释,请告诉我。

-Thanks

1 个答案:

答案 0 :(得分:3)

你将debounceTime放在错误的可观察对象上。目前它正在发送HTTP请求,然后将响应消除400ms(这实际上并没有做任何事情)。你真正想要的是使用debounceTime在字段本身上有一个valueChanged observable,然后在该订阅期间调用API。在没有看到你的其他代码的情况下,很难确切地知道它放在哪里,但是像:

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

希望这有帮助。

相关问题