可观察到的添加延迟 - Angular 2

Observable add delay - Angular 2

我正在实现一个注册页面。我想检查用户名是否已经存在。我正在尝试实现 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();
        });
  });
}

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

-谢谢

您将 debounceTime 置于错误的可观察对象上。目前它正在发送 HTTP 请求,然后将响应去抖动 400 毫秒(这实际上并没有做任何事情)。您真正想要的是在字段本身上有一个带有 debounceTime 的 valueChanged 可观察对象,然后在该订阅期间调用 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

希望这对您有所帮助。