如何在 angular 2 中为异步验证器添加去抖动时间? [英] How to add debounce time to an async validator in angular 2?
问题描述
这是我的异步验证器,它没有去抖动时间,我该如何添加?
This is my Async Validator it doesn't have a debounce time, how can I add it?
static emailExist(_signupService:SignupService) {
return (control:Control) => {
return new Promise((resolve, reject) => {
_signupService.checkEmail(control.value)
.subscribe(
data => {
if (data.response.available == true) {
resolve(null);
} else {
resolve({emailExist: true});
}
},
err => {
resolve({emailExist: true});
})
})
}
}
推荐答案
Angular 4+, Using Observable.timer(debounceTime)
:
@izupet 的回答是对的,但值得注意的是,当你使用 Observable 时它会更简单:
Angular 4+, Using Observable.timer(debounceTime)
:
@izupet 's answer is right but it is worth noticing that it is even simpler when you use Observable:
emailAvailability(control: Control) {
return Observable.timer(500).switchMap(()=>{
return this._service.checkEmail({email: control.value})
.mapTo(null)
.catch(err=>Observable.of({availability: true}));
});
}
由于 angular 4 已经发布,如果发送一个新值进行检查,Angular 会在它仍然在计时器中暂停时取消订阅 Observable
,因此您实际上不需要管理 setTimeout
/clearTimeout
逻辑自己.
Since angular 4 has been released, if a new value is sent for checking, Angular unsubscribes from Observable
while it's still paused in the timer, so you don't actually need to manage the setTimeout
/clearTimeout
logic by yourself.
使用 timer
和 Angular 的异步验证器行为,我们重新创建了 RxJS debounceTime
.
Using timer
and Angular's async validator behavior we have recreated RxJS debounceTime
.
这篇关于如何在 angular 2 中为异步验证器添加去抖动时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!