angular - debounceTime rxjs 运算符和输入 keyup 函数的 http 请求问题
问题描述
我正在尝试在 angular7 中实现服务器端搜索。我找到了一些代码来实现这一点,但不幸的是这不能按要求工作。当我搜索一个字符串时,它会发送多个 http 请求,但它应该只是一个 http 请求。这是我的代码。
fromEvent(this.simpleSearchInput.nativeElement, 'keyup').pipe(
debounceTime(500),
switchMap((search: any) => {
return this.usersService.simpleUserSearch(search.target.value);
})
).subscribe(res => {
this.queryUsers = res.result.data;
console.log('User Name is :' + res);
});
}
解决方案
这是我在某处找到的代码,它运行良好我使用 lodash 而不是使用 RXJS 库
脚步
1. 在你的组件 ts 文件中导入 debounce。
从“lodash”导入 { debounce };
2. 做私有财产
私有 debouncedFunction: any = null;
3. 在你的函数中使用 debouncedFunction
search(event: any) {
if (this.debouncedFunction) {
this.debouncedFunction.cancel();
}
this.debouncedFunction = debounce(() => {
console.log(event); // console.log will print event value after 1s of stop writing
}, 1000);
this.debouncedFunction();
}
推荐阅读
- javascript - 无法将序列化数据返回到可引用的 json 对象中
- python - 如何在 python 中将多个 3 维数组更改为单个 4 维数组?
- python - python scrapy检查类是否存在否则检查其他
- django - 在不访问数据库的情况下使用“登录用户”测试视图
- python - 如何将特殊键添加到键盘记录器 python
- android - Dart 中如何从 Https 服务器获取数据
- r - 如何安排 Cronjob 以执行文件中的所有 R 脚本
- reactjs - React Hooks:如何正确干净地使用Ref().current
- talend - 如何与 Talend Job 建立多个连接?
- python - 检查熊猫数据框中的下一个索引列值和相同值的连续长度