首页 > 解决方案 > 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);

    }); 
  }

标签: angulartypescripthttprxjsangular7

解决方案


这是我在某处找到的代码,它运行良好我使用 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();
  }

推荐阅读