2016-08-23 83 views
0

我正在實施註冊頁面。我想檢查用戶名是否已經存在。我試圖實現asyncvalidator,但每次用戶輸入一個字符時都會調用服務器,您是否可以在下面的代碼中幫助添加一些延遲,以便在用戶停止鍵入一段時間後僅以用戶名稱調用服務器?我讀了一些可觀察的debounceTime,但無法使其工作。可觀察的添加延遲 - 角2

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(); 
     }); 
    }); 
} 

請讓我知道,如果我可以更好地解釋。

- 感謝

+0

這裏是一個使用角度團隊debounceTime的示例https://angular.io/docs/ts/latest/guide/server-communication.html#!#more-observables希望這可以幫助 –

回答

3

你把debounceTime放在錯誤的observable上。目前它正在發送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 

希望這有助於。

+0

使用get方法代替find。因爲角4沒有找到方法 –