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函数用于对搜索结果进行格式化,你可以根据实际情况进行修改。

相关内容

热门资讯

透视黑科技"wepo... 透视黑科技"wepoker科技辅助器"详细辅助必赢教程(透视脚本免费app教程)是一款可以让一直输的...
透视好友房"wepo... 1、透视好友房"wepoker脚本下载"详细辅助玩家教程(免费脚本技巧);详细教程。2、wepoke...
透视有挂"aapok... 1、透视有挂"aapoker脚本"详细辅助必备教程(安装透视软件神器);详细教程。2、aapoker...
透视线上"wepok... 1、透视线上"wepoker私人局辅助挂"详细辅助黑科技教程(游戏下载软件)2、进入游戏-大厅左侧-...
透视安装"红龙pok... 1、透视安装"红龙poker辅助平台"详细辅助软件教程(手机版透视脚本技巧)。2、红龙poker辅助...
透视教学"约局吧德州... 透视教学"约局吧德州透视"详细辅助力荐教程(有机器人教程)关于约局吧德州透视机制的,其中提到了后台系...
透视玄学"wepok... 透视玄学"wepoker有辅助插件吗"详细辅助细节揭秘(如何下载安装包透明)1、点击下载安装,微扑克...
透视挂透视"德普之星... 此外,数据分析德州(德普之星私人局辅助免费)辅助神器app还具备辅助透视行为开挂功能,通过对客户德普...
透视了解"pokem... 透视了解"pokemomo辅助工具"详细辅助可靠技巧(黑侠破解技巧)1、点击下载安装,微扑克wpk插...
透视免费"wepok... 透视免费"wepoker私人定制透视"详细辅助总结教程(俱乐部辅助器透明);科技安装教程;13670...