Angular6 ngModelChange 中的去抖动时间 [英] Debouncetime in Angular6 ngModelChange

查看:20
本文介绍了Angular6 ngModelChange 中的去抖动时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Angular6 编写的复杂计算器应用程序,它根据 ngModelChange 事件中的多个输入计算结果,并直接在图表中显示这些结果.计算在服务器端完成.现在我想添加一个 debouncetime,这样服务器就不会在每次按下按键时都收到请求.

I have a complex calculator app written in Angular6 which calculates the results based of several inputs in the ngModelChange event and to show these results in charts directly. The calculation is done server side. Now I want to add a debouncetime, so the server dont receive a request with every key pressed.

我在 ngModelChange 中触发的计算方法如下所示:

My calculation method which is fires in the ngModelChange looks like this:

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),但似乎没有任何改变.

As you can see I already tried the debounceTime(5000) in my service but it seems like nothing has changed.

有人知道我如何解决这个问题吗?

Does anyone have an idea how I can solve this problem?

推荐答案

你总是可以使用 Subjects 来实现这个,如下所示:

you can always implement this using Subjects like below :

声明一个主题:

customInput : 主题<字符串>= new Subject();

在您的模板中:

(ngModelChange)='inputValueChanged($event)'

现在监听事件:

  inputValueChanged(event){
      this.customInput.next(event);
  }

您必须通过以下方式订阅您的主题:

You'll have to subscribe to your Subject in the below way :

this.customInput.debounceTime(300).distinctUntilChanged().subscribe(value =>{
       //value will have your input
    });

(有了这个,你的代码看起来整洁干净,也很有条理)

(with this your code will look neat and clean and also organised )

使用 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
});

这篇关于Angular6 ngModelChange 中的去抖动时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆