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

相关内容

热门资讯

透视举措!hhpoker软件安... 透视举措!hhpoker软件安装包(德普之星免费)本来是真的有辅助工具(哔哩哔哩)1、打开软件启动之...
透视窍门!hhpoker是真的... 透视窍门!hhpoker是真的吗(德普之星透视辅助)都是是有辅助方法(哔哩哔哩)运德普之星透视辅助辅...
透视演示!wepoker私人局... 透视演示!wepoker私人局辅助(WPK工具)都是真的是有辅助脚本(哔哩哔哩)透视演示!wepok...
透视要领!wepoker免费透... 透视要领!wepoker免费透视脚本(WePoKer看底牌)果然是有辅助工具(哔哩哔哩)1、实时we...
透视大纲!hh poker软件... 透视大纲!hh poker软件(HHpoker控制)真是有辅助插件(哔哩哔哩);1、hh poker...
透视秘籍!德普之星私人局透视(... 透视秘籍!德普之星私人局透视(德普之星透视辅助)本来存在有辅助脚本(哔哩哔哩)德普之星私人局透视透视...
透视要领!德普之星怎么设置埋牌... 透视要领!德普之星怎么设置埋牌(WPK俱乐部)一直真的是有辅助神器(哔哩哔哩)1)德普之星怎么设置埋...
透视经验!we-poker是什... 透视经验!we-poker是什么软件(AApoker辅助插件)本来真的是有辅助神器(哔哩哔哩)1、玩...
透视窍门!wepoker私人局... 透视窍门!wepoker私人局辅助(WePoKer轻量版)总是存在有辅助插件(哔哩哔哩)运wepok...
透视练习!wepoker破解游... 透视练习!wepoker破解游戏盒子(WePoKer插件)都是是真的有辅助教程(哔哩哔哩)1、透视练...