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

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

问题描述

我有一个用Angular6编写的复杂计算器应用程序,该应用程序基于ngModelChange事件中的多个输入来计算结果,并将这些结果直接显示在图表中。计算是在服务器端完成的。现在,我想添加一个去抖时间,以便服务器在按下每个键时都不会收到请求。

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:主题< string> = 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天全站免登陆