[英]Angular2 async validator for username input field
我正在嘗試驗證是否使用了用戶名,並將結果分配給布爾值:
isUsernameAvailable(control: FormControl) {
this.authenticationService.isUsernameAvailable(control.value)
.subscribe(
result => console.log(result.taken),
error => console.log(error)
);
}
這將使用輸入字符串,並返回一個布爾值,無論它是否與數據庫中的用戶匹配。 使用字符串調用時,它可以按預期工作,但是我想使用字段輸入作為參數來調用它,如下所示:
this.username = new FormControl(null,
Validators.compose([
Validators.required,
Validators.minLength(3),
]),this.isUsernameAvailable(this.username.value)); // <-- this is wrong obviously
我發現將其添加到ngOnInit()時可以使用:
this.username.valueChanges.debounceTime(400).subscribe(value => {return this.isUsernameAvailable(value) });
所以我的問題是如何做到這一點,以便我的驗證器從輸入字段中獲取輸入文本,並檢查是否使用了用戶名。 編輯:當我只使用this.isUsernameAvailable我得到
“無法讀取未定義的屬性'authenticationService'”錯誤
。 我也嘗試將其綁定:this.isUsernameAvailable.bind(this),但隨后我得到了
無法讀取未定義錯誤的屬性“訂閱”
我也將代碼更新為上次修改的代碼。 (控制台日志報告正確的值,但驗證器返回錯誤)。
因此,顯然我只是不知道自己在做什么,但是我以某種方式使它工作了。 如果有人遇到相同的問題,我將粘貼我的解決方案。 我的最終代碼是:
this.username = new FormControl(null, [
Validators.required,
Validators.pattern(this.usernamePattern),
Validators.minLength(3),
Validators.maxLength(15)
], this.validateUsername.bind(this)
);
validateUsername(c: FormControl) {
return this.usernameAvailable(c.value);
}
private validationTimeout: any;
usernameAvailable(username: string) {
clearTimeout(this.validationTimeout);
return new Promise((resolve) => {
this.validationTimeout = setTimeout(() => {
let req = this.authenticationService.isUsernameAvailable(username);
req.subscribe(result => {
if (result.taken) {
resolve({taken: true})
}
else {
resolve(null)
}
},
error => this.logger.error(error.message))
}, 600);
});
}
請記住,您不能直接在異步驗證器上使用debounceTime,因為它總是在每次擊鍵后立即啟動,因此您必須以某種方式使請求超時。 可能有更好的方法,這對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.