我有一个用 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 ,
完整的例子可以找到here
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged} from 'rxjs/operators';
this.customInput.pipe(debounceTime(300),distinctUntilChanged()).subscribe(value =>{
//value will have your input
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)