Angular-debounceTime()和distinctUntilChanged()似乎有问题
我有一个验证器,问题是即使我有去BounceTime,500毫秒后它会运行所有的击键Angular-debounceTime()和distinctUntilChanged()似乎有问题,angular,rxjs,angular-validation,Angular,Rxjs,Angular Validation,我有一个验证器,问题是即使我有去BounceTime,500毫秒后它会运行所有的击键 slugTaken(model) { return control => new Promise((resolve, reject) => { let id = control.parent.controls._id.value; return control.valueChanges.debounceTime(500).distinctUntilChange
slugTaken(model) {
return control => new Promise((resolve, reject) => {
let id = control.parent.controls._id.value;
return control.valueChanges.debounceTime(500).distinctUntilChanged().subscribe(() => {
this.httpClient.post('/api/slug', {id: id, slug: control.value, model: model, _loading: 1}).subscribe((res: any) => {
if (res.data > 0)
resolve({'duplicated': true});
else
resolve(null);
})
});
});
}
因此,我添加了一个超时来修复错误
slugTaken(model) {
return control => new Promise((resolve, reject) => {
let id = control.parent.controls._id.value;
let $this = this;
return control.valueChanges.debounceTime(500).distinctUntilChanged().subscribe(() => {
clearTimeout(this.timeout);
this.timeout = setTimeout(function(){
$this.httpClient.post('/api/slug', {id: id, slug: control.value, model: model, _loading: 1}).subscribe((res: any) => {
if (res.data > 0)
resolve({'duplicated': true});
else
resolve(null);
})
});
}, 500)
});
}
但我认为rxjs有一个更好的解决方案
有什么建议吗?这就是我如何调用验证器的
this.form = this.fb.group({
_id: [],
name: [null, Validators.required],
slug: [null, [Validators.required], [this.validatorsService.slugTaken('transporters')]],
transport_type_id: [],
forthcrs_code: [],
logoname: []
});
你期待什么?尝试
throttleTime
而不是debounceTime
Nope。。。在最后一个keystoke之后500毫秒,它使用相同的密钥(所有5个字符,不单独)触发例如5个http请求。(如果我键入5个字符)毫无疑问,您正在多次呼叫slugtake
。debounceTime
和distinctUntilChanged
的RxJS实现工作正常;问题不在于它们的实现。而且,至少可以说,像你所做的那样,将一个可观察到的东西包装在承诺中是一种反模式。要对此负责,您需要包含更多代码,指示您何时以及多久调用slugtake
。我在第一篇文章中添加了我调用slugtake的方式