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

相关内容

热门资讯

分辨真假!hh poker辅助... 分辨真假!hh poker辅助器先试用,wejoker辅助器怎么卖,一直真的有挂(有挂分析)1、每一...
研究成果!wpk俱乐部辅助器,... 研究成果!wpk俱乐部辅助器,werplan免费挂下载,竟然真的是有挂(发现有挂)1、每一步都需要思...
推荐一款!智星德州插件,wep... 推荐一款!智星德州插件,wepoker好友房开挂,好像有挂(有挂辅助)1. 选牌创建新账号,点击进入...
一分钟揭秘!wpk模拟器多开,... 一分钟揭秘!wpk模拟器多开,德普之星辅助器,竟然有挂(有挂攻略)1、德普之星辅助器破解器简单,德普...
玩家必用!德普之星辅助工具如何... 玩家必用!德普之星辅助工具如何打开,德州透视插件,都是是真的有挂(有挂方针)1、完成有辅助插件,帮助...
玩家必用!德州局透视脚本免费版... 玩家必用!德州局透视脚本免费版下载手机版,德州机器人代打脚本,切实是真的有挂(有挂分享)1、让任何用...
最新研发!hhpoker可以开... 最新研发!hhpoker可以开挂吗,wepoker祈福有用吗,真是存在有挂(有挂教程)1、下载好正确...
热点推荐!werplan免费挂... 热点推荐!werplan免费挂下载,红龙poker辅助器免费观看,原来存在有挂(有挂猫腻)1、完成辅...
一分钟教你!aa poker辅... 一分钟教你!aa poker辅助包,pokeplus脚本,真是真的有挂(有挂技巧)1、用户打开应用后...
交流学习经验!wepoker破... 交流学习经验!wepoker破解器,pokemmo辅助器,都是真的是有挂(有挂教程)1、打开软件启动...