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透视脚本免费,wepoker免费永久脚本,新手必备(有挂教程)1、这是跨平台...
透视辅助!德普之星辅助功能如何... 透视辅助!德普之星辅助功能如何打开,德州辅助工具到底怎么样,可靠教程(原先真的是有挂);大神普及一款...
透视总结!aapoker透视脚... 透视总结!aapoker透视脚本下载,智星德州菠萝透视插件工具,一分钟快速了解(有挂了解);是一款可...
透视了解!红龙poker透视,... 相信很多朋友都在电脑上玩过红龙poker透视吧,但是很多朋友都在抱怨用电脑玩起来不方便。为此小编给大...
透视苹果版!wpk透视辅助方法... 您好,wpk透视辅助方法这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家...
透视安卓版!wpk透视脚本链接... 透视安卓版!wpk透视脚本链接,红龙poker作弊指令,实测分享(有挂教程);红龙poker作弊指令...
透视插件!wpk辅助软件多少钱... 透视插件!wpk辅助软件多少钱一个,wepoker黑侠破解,普及教程(原来是有挂);玩家必备必赢加哟...
透视了解!wepoker底牌透... 一、wepoker底牌透视脚本app简介了解软件请加微:136704302wepoker底牌透视脚本...
透视挂透视!wepoker透视... 透视挂透视!wepoker透视脚本免费,hh poker透视器下载,力荐教程(好像是有挂);原来确实...
透视讲解!aapoker有脚本... 透视讲解!aapoker有脚本吗,约局吧德州真的存在透视吗,解密教程(固有有挂)科技教程也叫必备教程...