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

相关内容

热门资讯

透视开挂!aapoker透视插... 透视开挂!aapoker透视插件,aapoker真的假的(透视)一直是有挂(哔哩哔哩)1、免费脚本咨...
透视教程书!hhpoker外g... 透视教程书!hhpoker外g挂靠谱吗,HHpoker透视器切实真的有工具,九分钟教程(真实有挂)1...
透视技法!德普之星透视软件免费... 透视技法!德普之星透视软件免费入口官网,德普之星下载原来存在有开挂,第九分钟教程(真的有挂)1、全新...
透视方案!德普之星透视辅助软件... 透视方案!德普之星透视辅助软件是真的吗,德普之星安卓版总是真的是有神器,四分钟教程(果真有挂)1.德...
透视经验!wpk透视辅助方法,... 透视经验!wpk透视辅助方法,WPK靠谱总是真的是有神器,第7分钟教程(有挂分享)1、许多玩家不知道...
透视绝活儿!pokemmo脚本... 透视绝活儿!pokemmo脚本手机版,WePoKer助手确实存在有透视,十分钟教程(真是有挂)1、p...
透视手段!德扑圈透视挂,德扑之... 透视手段!德扑圈透视挂,德扑之心透视好像存在有下载,1分钟教程(揭秘有挂)1、全新机制【德扑圈透视挂...
透视法门!黑侠破解wepoke... 透视法门!黑侠破解wepoker,WePoKer程序一直真的有工具,第二分钟教程(有挂透明挂)所有人...
透视妙招!德州局HHpoker... 透视妙招!德州局HHpoker透视脚本,HHpoker德州局总是是有下载,九分钟教程(了解有挂)亲,...
透视要领!hhpoker是正规... 透视要领!hhpoker是正规的吗,HHpoker脚本挂原来真的有安装,十分钟教程(有挂功能)1、玩...