【问题标题】:Clear timeout with every function call Angular2 RxJS清除每个函数调用Angular2 RxJS的超时
【发布时间】:2017-03-08 11:53:46
【问题描述】:

我有一个 http 请求,如果用户在输入中输入至少 4 个字符,并且每次更改其内容(添加/删除字母)时都会触发该请求。我想添加一个超时,如果用户开始输入字符,该函数将等待 1 秒直到它触发请求,以避免在用户快速输入时出现大量请求。我的尝试:

if (this.pointName.length >= 3) {
  let timer = function() {
    this.http.get(`./points.json`)
        .subscribe(res => {
            this.pointsArray = res.json();
        });
    };
clearTimeout(timer); 
setTimeout(timer,1000);

我的想法是清除每个keyup 事件的超时并再次设置它。 但不幸的是,它给了我一个错误,'() => void' 类型的参数不能分配给'number' 类型的参数。

有没有什么方法可以提高效率?也许使用 RxJS?无论如何,我正在寻找一个可行的解决方案。提前谢谢你。

HTML

 <input type="text" id="searchInput" placeholder="Point name"(keyup)="getPoints()">

【问题讨论】:

  • 更好的方案是使用 rxjs debounce 运算符。

标签: javascript angular typescript rxjs scadalts


【解决方案1】:

为什么不使用 debounceTime(500) 而不是 setTimeout。

https://www.learnrxjs.io/operators/filtering/debouncetime.html

【讨论】:

【解决方案2】:

首先,你最好在 RxJS 中使用Debounce 操作符。 您的代码中的问题是您应该将timer_id 传递给clearTimeout 而不是函数。

if (this.pointName.length >= 3) {
  let timer = function() {
    this.http.get(`./points.json`)
        .subscribe(res => {
            this.pointsArray = res.json();
        });
    };
let timer_id = undefined;
clearTimeout(timer_id); 
timer_id = setTimeout(timer,1000);

【讨论】:

    【解决方案3】:

    试试这个:

    创建一个 RxJS 主题作为组件的新成员变量

    searchTerm$ = new Subject<string>();
    

    在你组件的 ngOnInit 方法中,设置你的 observable,

    ngOnInit() {
      this.searchTerm$
          .filter( value => value.length >= 3)
          .debounceTime(1000)
          .switchMap( val => {
             return this.http.get('./points.json')
                             .map(result => result.json());
           })
          .subscribe(result => .... // do what you want with the response );
    } 
    

    在您的 HTML 中,更改您的 keyup 事件绑定以提交您的输入字段的值

     <input type="text" id="searchInput" placeholder="Point name"(keyup)="getPoints(this.value)">
    

    然后在组件的 getPoints 方法中,将值发送到您的主题$

    getPoints(value) {
      this.subject$.next(value);
    }
    

    基本上,您创建的 observable 做了几件事:

     searchTerm$
      .filter( value => value.length >= 3)   // 1 filter out search terms that are shorter than 3 characters
      .debounceTime(1000)                    // 2. only send events after no event comes for 1 sec
      .switchMap( val => {                    // 3. convert your value to the result of your http request
         return this.http.get('./points.json')
                         .map(result => result.json());
       })
      .subscribe(result => .... // do what you want with the response );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2022-01-12
      • 2015-06-21
      • 1970-01-01
      • 2017-06-02
      • 2014-08-20
      相关资源
      最近更新 更多