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

相关内容

热门资讯

透视规律!wpk官网下载链接,... 透视规律!wpk官网下载链接,佛手在线大菠萝为什么都输,手段教程(好像是有挂)-哔哩哔哩透视规律!w...
透视靠谱!黑侠破解wepoke... 透视靠谱!黑侠破解wepoker(透视)开挂辅助app(切实真的是有挂)-哔哩哔哩1、黑侠破解wep...
透视系统!德扑圈透视,德州局透... 透视系统!德扑圈透视,德州局透视,要领教程(一贯存在有挂)-哔哩哔哩;1、该软件可以轻松地帮助玩家将...
透视机器人!wepoker私人... 透视机器人!wepoker私人局透视教程(透视)开挂辅助挂(都是真的有挂)-哔哩哔哩1、玩家可以在w...
透视智能ai!wepoker私... 透视智能ai!wepoker私人局俱乐部怎么进,wepoker透视有用吗,练习教程(一贯是真的挂)-...
透视神器!wepoker插件功... 透视神器!wepoker插件功能辅助器(透视)开挂辅助技巧(好像是真的挂)-哔哩哔哩暗藏猫腻,小编详...
透视工具!wepoker底牌透... 透视工具!wepoker底牌透视,wpk透视工作室,妙招教程(一贯真的有挂)-哔哩哔哩透视工具!we...
透视数据!wepoker游戏的... 透视数据!wepoker游戏的安装教程(透视)开挂辅助方法(本来是真的挂)-哔哩哔哩运wepoker...
透视黑科技!wepoker怎么... 透视黑科技!wepoker怎么破解游戏,uupoker有透视吗,方式教程(一贯真的有挂)-哔哩哔哩1...
透视猫腻!智星德州插件2024... 透视猫腻!智星德州插件2024最新版(透视)开挂辅助工具(真是是有挂)-哔哩哔哩一、智星德州插件20...