使用场景:
根据input输入内容,实时查询api接口。
思路流程:
通常对于输入内容做以下一系列操作:
1.监听input输入值;
2.去除输入值两端空格键,判断是否满足最小输入长度;
3.debounce.即不是在每次击键时发送api请求,而是等待击键的中断;
4.输入值相同时不发送api请求;
5如果更新后的结果无效,则取消正在进行的ajax请求;
例子:
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
const searchBox = document.getElementById('search-box');
const typehead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => e.target.value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);
typehead.subscribe(
data => {
//handle the data from the api
}
);
原文及参考: