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

相关内容

热门资讯

终于知道!德普之星app安卓版... 终于知道!德普之星app安卓版破解版(辅助挂)果然有挂(的确有挂辅助器)辅助器是一种具有地方特色的麻...
玩家必看科普!hhpoker有... 玩家必看科普!hhpoker有没有外挂(辅助挂)本来是有挂(有挂神器辅助攻略)1、免费脚本咨询教程、...
交流学习经验!hhpoker脚... 交流学习经验!hhpoker脚本下载(辅助挂)真是是真的有挂(有挂方式辅助软件)1、许多玩家不知道辅...
热点推荐!we poker插件... 热点推荐!we poker插件(辅助挂)都是有挂(有挂功能辅助攻略)1、进入游戏-大厅左侧-新手福利...
终于懂了!wepoker怎么看... 终于懂了!wepoker怎么看牌型(辅助挂)切实有挂(真的有挂辅助工具)1、下载好正确养号方法之后点...
玩家攻略!hhpoker免费透... 玩家攻略!hhpoker免费透视脚本(辅助挂)本来真的有挂(有挂细节辅助app)1、透视辅助软件激活...
一分钟带你了解!哈糖大菠萝可以... 一分钟带你了解!哈糖大菠萝可以开挂吗(辅助挂)竟然真的有挂(有挂分析辅助插件)1、进入游戏-大厅左侧...
玩家实测!德州辅助工具到底怎么... 玩家实测!德州辅助工具到底怎么样(辅助挂)其实真的有挂(有挂技巧辅助工具)1、实时透视辅助更新:用户...
玩家科普!wepoker买钻石... 玩家科普!wepoker买钻石有用吗(辅助挂)原来真的是有挂(有挂攻略辅助攻略)1、玩家可以在透视最...
一秒答解!哈糖大菠萝有挂吗5个... 一秒答解!哈糖大菠萝有挂吗5个常用方法(辅助挂)本来真的有挂(有挂秘诀辅助技巧)一、可以开透视的定义...