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

相关内容

热门资讯

透视分享"德州透视竞... 透视分享"德州透视竞技联盟"竟然存在有辅助教程(哔哩哔哩)1、德州透视竞技联盟脚本辅助下载、德州透视...
透视解密"wepok... 透视解密"wepoker有透视功能吗"本来是有辅助攻略(哔哩哔哩)wepoker有透视功能吗脚本下载...
透视必备"wepok... 透视必备"wepoker私人局透视插件"一直是有辅助攻略(哔哩哔哩)1、wepoker私人局透视插件...
透视普及"哈糖大菠萝... 透视普及"哈糖大菠萝免费辅助器"总是真的是有辅助神器(哔哩哔哩)1、该软件可以轻松地帮助玩家将哈糖大...
透视推荐"竞技联盟辅... 透视推荐"竞技联盟辅助插件"好像真的是有辅助挂(哔哩哔哩)1、任何竞技联盟辅助插件透视是真的假的的玩...
透视关于"hhpok... 透视关于"hhpoker万能辅助器"切实是真的辅助攻略(哔哩哔哩)hhpoker万能辅助器脚本下载中...
透视详细"wpk模拟... 透视详细"wpk模拟器是什么"其实存在有辅助神器(哔哩哔哩)1、完成wpk模拟器是什么有辅助插件,帮...
透视解密"hhpok... 透视解密"hhpoker真能买到挂吗"竟然是有辅助挂(哔哩哔哩)1、下载好hhpoker真能买到挂吗...
透视专业"红龙pok... 透视专业"红龙poker辅助平台"好像存在有辅助软件(哔哩哔哩)暗藏猫腻,小编详细说明红龙poker...
透视曝光"福建大菠萝... 透视曝光"福建大菠萝万能辅助器"果然有辅助攻略(哔哩哔哩)1、玩家可以在福建大菠萝万能辅助器线上大神...