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

相关内容

热门资讯

据报道"aapoke... 据报道"aapoker辅助器是真的吗"HH平台挂(好像真的有辅助辅助器)-哔哩哔哩1、下载好aapo...
透视脚本"wepok... 透视脚本"wepoker私人局透视教程"hhpoker辅助挂(都是存在有辅助下载)-哔哩哔哩1、we...
目前来看"pokem... 目前来看"pokemmo辅助器手机版下载"wepoker有辅助器吗(确实是有辅助软件)-哔哩哔哩1、...
这一问题亟待解决"h... 这一问题亟待解决"hh poker软件"wejoker内置辅助(确实真的有辅助插件)-哔哩哔哩1、每...
一直以来"hhpok... 一直以来"hhpoker德州有挂吗"werplan外开挂(切实是有辅助平台)-哔哩哔哩1、操作简单,...
据监测"大菠萝789... 据监测"大菠萝789辅助器下载"hhpoker有透视功能吗(切实是真的辅助平台)-哔哩哔哩1、大菠萝...
截至目前"wepok... 截至目前"wepoker软件安装包"wpk透视辅助下载(好像真的有辅助修改器)-哔哩哔哩wepoke...
备受关注的"hhpo... 备受关注的"hhpoker免费透视脚本"德扑圈透视(原来是有辅助插件)-哔哩哔哩1、hhpoker免...
透视插件"wepok... 透视插件"wepoker免费脚本咨询"wepoker代打辅助(真是是有辅助软件)-哔哩哔哩1、wep...
据文件显示"德普之星... 据文件显示"德普之星透视辅助软件"wepoker透视脚本免费使用视频(竟然是真的辅助插件)-哔哩哔哩...