angular - Angular6 ngModelChange 中的去抖时间

标签 angular typescript rxjs angular6 debouncing

我有一个用 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
});

关于angular - Angular6 ngModelChange 中的去抖时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51780025/

相关文章:

angular - 如何用新的 observable 替换 http observable?

angular - Jasmine-core 避免安装 angular-devkit/build-angular

javascript - webpack:在解析模块之前必须手动执行 TSC

angular - 我如何捕获 ng-reflect-value 的值来测试其预期值?

angular - 避免在 Angular 的 [src] 中重新加载图像

functional-programming - 创建一个通过过滤器的连续值流

angular - 在 Angular 中过滤响应对象

javascript - Angular2 - 模块与组件有何不同?

typescript - 如何使用函数返回的类作为 TypeScript 中的类型?

ReactJS typescript 错误Parameter props implicitly has 'any' type