我正在使用 debounceTime
在下拉列表中获取列表,到目前为止一切正常我输入了三个字符并触发 api 调用返回给我一个列表,但问题是当我从 Control 的 valueChanges
列表中选择一项会导致再次调用,这是不必要的。如何预防?
这是我的代码:
this.myForm.controls['control'].valueChanges.pipe(
filter(text => text.length > 2),
debounceTime(1000),
distinctUntilChanged()).subscribe((value: string) => {
this.getItem(value);
});
最佳答案
我认为最好为您正在寻找文本输入的表单控件提供一个 Id,如下所示:
<input type="text" id="inputText">
然后只使用该表单控件在输入时获取数据,如下例所示:
ngOnInit() {
const inputText = document.getElementById('inputText');
const typeahead = fromEvent(inputText, 'input').pipe(
map((e: KeyboardEvent) => (<HTMLInputElement>e.target).value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged()
);
typeahead.subscribe(data => {
this.getItem(data);
});
}
然后它只会在你在那个输入表单 Controller 上打字时触发
关于javascript - debounceTime 使表单控件运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59242937/