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

相关内容

热门资讯

最新消息!pokerworld... 最新消息!pokerworld修改器(透视)皮皮辅助软件是真的吗(其实有辅助神器)-哔哩哔哩1、金币...
据相关数据显示!拱趴游戏破解器... 据相关数据显示!拱趴游戏破解器(透视)小程序牵手跑得辅助器下载(总是存在有辅助平台)-哔哩哔哩进入游...
针对!wpk软件是正规的吗(透... 针对!wpk软件是正规的吗(透视)宝宝浙江辅助器(总是存在有辅助安装)-哔哩哔哩1、起透看视 宝宝浙...
透视美元局!wepokerpl... 透视美元局!wepokerplus透视脚本免费(透视)邳州友友有没有辅助软件(竟然存在有辅助工具)-...
有玩家发现!wejoker辅助... 有玩家发现!wejoker辅助脚本(透视)指尖四川刷无限钻石(其实真的有辅助安装)-哔哩哔哩1、指尖...
透视数据!红龙poker辅助(... 透视数据!红龙poker辅助(透视)老友广东辅助工具下载(原来真的有辅助修改器)-哔哩哔哩所有人都在...
透视存在!来玩app破解版(透... 透视存在!来玩app破解版(透视)透视辅助器免费欢聚水鱼(果然存在有辅助软件)-哔哩哔哩;1、透视辅...
这一现象值得深思!hhpoke... 这一现象值得深思!hhpoker德州挂真的有吗(透视)河洛杠次插件(原来存在有辅助修改器)-哔哩哔哩...
事发当天!wepoker永久免... 事发当天!wepoker永久免费脚本(透视)小闲川南手游辅助器(真是存在有辅助安装)-哔哩哔哩1、该...
无独有偶!pokemmo脚本(... 无独有偶!pokemmo脚本(透视)新道游辅助器透视挂(其实是有辅助辅助器)-哔哩哔哩进入游戏-大厅...