【问题标题】:Avoiding duplicate calls inside keyup event in angular避免在 Angular 中的 keyup 事件中重复调用
【发布时间】:2021-07-21 10:37:24
【问题描述】:

我想做的是

  1. 调用服务并在 ngOnit() 上绑定数据
  2. 在给定的文本框中,当用户键入内容时,不是为每个字母调用 API 调用,而是等待一秒钟,如果用户没有进一步键入,则进行 API 调用(需要在用户笔画之间去抖动)。
  3. 搜索完成后,我想将数据绑定回来。

问题:对于下面的 API 调用,对于相同的搜索关键字进行了 3 到 4 次调用,我想进行 1 次调用,任何帮助将不胜感激,谢谢。

在我的 html 文件中

<div *ngIf=let result in result$ | async>
  
</div>
<input type="text" (keyup)="filterData($event)">

在我的组件文件中

ngOnInit(){

this.result$ =  someServiceCall(); //result$ is an observable
}

filterData(event)
{
  fromEvent(event.target, 'keyup')
  .pipe(debounceTime(1000), distinctUntilChanged(),
  mergeMap((search) => {
    this.result$ = someServiceCall(event.target.value)
    }))
observable.subscribe(value) => {
})
}
return this.result$
}

【问题讨论】:

    标签: angular rxjs angular-material rxjs5 rxjs-observables


    【解决方案1】:

    您所做的是多次创建 observable 作为用户输入。 你应该创建一个像 filterThrottle = new Subject&lt;string&gt;(); 这样的主题,然后在 ngOnInit 中订阅它

    this.filterThrottle.pipe(debounceTime(1000)).subscribe((input) => {
     // Do something with input
    });
    

    在 html 中像这样发出

    <input type="text" (keyup)="filterThrottle.next($event)">
    

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多