angular - Angular6 ngModelChange 中的去抖动时间
问题描述
我有一个用 Angular6 编写的复杂计算器应用程序,它根据 ngModelChange 事件中的几个输入计算结果,并直接在图表中显示这些结果。计算在服务器端完成。现在我想添加一个去抖动时间,所以服务器不会在按下每个键时收到请求。
我在 ngModelChange 中触发的计算方法如下所示:
async calculate(){
if(this.checkInputs()){
try{
let returnDto = await this.webApiService.calculate(new CalculatorInputDto(this.model)).toPromise();
this.outputCalculate.emit(returnDto);
}
catch(e){
console.log(e);
}
}
还有我的服务方法:
calculate(dto: CalculatorInputDto): Observable<any> {
let url = this.baseUrl + "calculate";
return this.http.post(url, JSON.stringify(dto), this.options)
.pipe(
debounceTime(5000),
map((res => res.json())),
catchError(error => this.handleError(error))
);
}
如您所见,我已经在我的服务中尝试了 debounceTime(5000),但似乎没有任何改变。
有谁知道我该如何解决这个问题?
解决方案
您始终可以使用Subjects
如下方式实现此目的:
声明一个主题:
customInput : Subject<string> = new Subject();
在您的模板中:
(ngModelChange)='inputValueChanged($event)'
所以现在收听事件:
inputValueChanged(event){
this.customInput.next(event);
}
您必须通过以下方式订阅您的主题:
this.customInput.debounceTime(300).distinctUntilChanged().subscribe(value =>{
//value will have your input
});
(有了这个,你的代码看起来整洁干净,也很有条理)
编辑:使用 rxjs >= v6 ,
完整的例子可以在这里找到
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged} from 'rxjs/operators';
this.customInput.pipe(debounceTime(300),distinctUntilChanged()).subscribe(value =>{
//value will have your input
});
推荐阅读
- linux - 如何在 Linux 的 VS CODE 中打开我的 GIT REPO
- javascript - php 获取 document.getelementbyid 的值
- c# - Visual Studio 有时会在 PC 重新启动后重建未修改的项目
- javascript - 避免在第一次 ajax 调用完成之前通过 ajax 请求提交多个表单
- java - 为什么在while循环中等待条件?
- jquery - 获取数组 jquery 中单个 JSON 对象值的总和
- python - python "is" 和 "==" 问题
- dialogflow-es - 如何在对话流中构建许多问题意图
- android - 如何以编程方式在 LinearLayout 中添加边距/填充?
- c - 替换linux内核中使用的container_of宏