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、每一步都...
今天上午!wejoker手机版... 今天上午!wejoker手机版透视脚本,newpoker怎么安装脚本,讲义教程(真是有挂)-哔哩哔哩...
据统计!hhpoker可以开挂... 据统计!hhpoker可以开挂吗(透视)一直真的有挂(有挂详细开挂辅助辅助器)-哔哩哔哩1、上手简单...
刚刚!约局吧德州真的存在透视吗... 刚刚!约局吧德州真的存在透视吗,pokemmo辅助工具,教材教程(今日头条)-哔哩哔哩1、约局吧德州...
据报道!哈糖大菠萝免费辅助器(... 据报道!哈糖大菠萝免费辅助器(透视)原来真的是有挂(有挂教学开挂辅助插件)-哔哩哔哩1、哈糖大菠萝免...
近日!wpk透视辅助下载,we... 近日!wpk透视辅助下载,wepoker透视脚本苹果版,机巧教程(真的有挂)-哔哩哔哩进入游戏-大厅...
来临!竞技联盟辅助(透视)原来... 来临!竞技联盟辅助(透视)原来真的是有挂(确实有挂开挂辅助平台)-哔哩哔哩1)竞技联盟辅助辅助挂:进...
据公告内容!pokemmo脚本... 据公告内容!pokemmo脚本,拱趴大菠萝有什么挂,技法教程(有挂方略)-哔哩哔哩1、拱趴大菠萝有什...
此事迅速冲上热搜!拱趴大菠萝万... 此事迅速冲上热搜!拱趴大菠萝万能挂(透视)一贯真的有挂(有挂分析开挂辅助插件)-哔哩哔哩1、下载好拱...
备受关注的!WePoKer辅助... 备受关注的!WePoKer辅助器,hhpoker有辅助吗,模块教程(确实有挂)-哔哩哔哩1、游戏颠覆...