Angulartypeaheaddebouncetimerequest
创始人
2024-10-29 20:01:04
0

在Angular中使用debounceTime对typeahead搜索输入进行节流,减少请求次数。

在HTML模板中,通过ngbTypeahead指令绑定搜索输入,并使用debounceTime方法对搜索输入进行节流:


在组件中,定义搜索函数search并在其中使用debounceTime方法:

import { Component } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  searchTerm: string;
  searchTerms = new Subject();

  search = (text$: Observable) => {
    return text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap(term => this.searchTerms(term))
    );
  }

  constructor() {
    this.searchTerms.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap(term => this.search(term))
    ).subscribe(results => {
      console.log(results);
    });
  }

  search(term: string): Observable {
    // place your http request here
    return of([]);
  }

  formatter(result) {
    // place your formatter here
    return result;
  }
}

此方法使用rxjs的Subject及相应的操作符来对输入进行节流和去重,最终返回一个Observable来获取搜索结果。你可以在search函数中进行实际的搜索请求,也可以使用rxjs的of函数来返回一个静态的结果集。示例代码中的formatter函数用于对搜索结果进行格式化,你可以根据实际情况进行修改。

相关内容

热门资讯

外挂课程!wepoker安装教... 外挂课程!wepoker安装教程,sohoopoker辅助-一贯存在有辅助脚本(哔哩哔哩)wepok...
外挂教程书!pokerworl... 外挂教程书!pokerworld修改器,拱趴大菠萝万能挂-原来一直都是有辅助技巧(哔哩哔哩)外挂教程...
外挂妙招!德州私人局怎么透视,... 外挂妙招!德州私人局怎么透视,约局吧如何查看是否有挂-其实一直都是有辅助教程(哔哩哔哩)1、超多福利...
外挂积累!约局吧德州透视,po... 外挂积累!约局吧德州透视,poker world辅助器-本来有辅助插件(哔哩哔哩)约局吧德州透视辅助...
外挂学习!德州透视脚本,aa ... 外挂学习!德州透视脚本,aa poker辅助-一直一直总是有辅助插件(哔哩哔哩)1、这是跨平台的德州...
外挂模块!德州局脚本,xpok... 外挂模块!德州局脚本,xpoker辅助器-真是一直总是有辅助技巧(哔哩哔哩)1、起透看视 德州局脚本...
外挂法子!德普之星透视辅助软件... 外挂法子!德普之星透视辅助软件是真的吗,哈糖大菠萝可以开挂吗-真是是有辅助方法(哔哩哔哩)1、哈糖大...
外挂方针!竞技联盟破解版最新版... 外挂方针!竞技联盟破解版最新版,xpoker辅助-确实存在有辅助技巧(哔哩哔哩)1、该软件可以轻松地...
外挂攻略!红龙poker辅助,... 外挂攻略!红龙poker辅助,德普之星透视-真是有辅助脚本(哔哩哔哩)1、红龙poker辅助公共底牌...
外挂妙招!uupoker透视,... 外挂妙招!uupoker透视,sohoo开挂辅助-确实有辅助方法(哔哩哔哩);sohoo开挂辅助破解...