Angular:检测用户停止输入时

huangapple go评论85阅读模式
英文:

Angular: Detect when user has stopped typing

问题

我有一个文本框作为输入元素,想知道用户何时停止输入以进行REST调用。我阅读了一些帖子,建议在键盘抬起事件上使用setTimeout;然而,当用户停止输入一段时间后,我发现API被多次调用(取决于输入内容的长度)。是否有其他方法可以检测用户何时停止输入以进行API调用?

英文:

I have a textbox as an input element and would like to know when the user has stopped typing to make REST call. I read some posts to use setTimeout on keyup; however, then user has stopped typing for a certain amount time, I see that the API is getting called numerous times (depending on the length of what is typed). Is there any other way to detect that the user has stopped typing to make an API call?

答案1

得分: 1

debounceTime 延迟源 Observable 发出的值,延迟时间以您指定的毫秒数作为其参数。

import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';

// 元素引用
const searchBox = document.getElementById('search');

// 流
const keyup$ = fromEvent(searchBox, 'keyup');

// 在按键后等待 0.5 秒以发出当前值
keyup$.pipe(
  map((i: any) => i.currentTarget.value),
  debounceTime(500)
)
.subscribe((value) => {
  console.log('value is', value);
});

现在在 subscribe 体中,您可以进行 API 调用。

英文:

Okay, This will help you out for sure and it is very easy to use:-

debounceTime

debounceTime delays the value emitted by the source Observable for the time in milliseconds you specified as its parameter.

--index.ts--

import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';

// elem ref
const searchBox = document.getElementById('search');

// streams
const keyup$ = fromEvent(searchBox, 'keyup')

// wait .5s between keyups to emit current value
keyup$.pipe(
  map((i: any) => i.currentTarget.value),
  debounceTime(500)
)
.subscribe((value) => {
  console.log('value is', value);
});

--index.html--

<input type="text" id="search" />

Now in the subscribe body you can make your api call.

huangapple
  • 本文由 发表于 2020年8月13日 07:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63385970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定