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

相关内容

热门资讯

出乎意料的是!hhpoker脚... 出乎意料的是!hhpoker脚本(透视)多乐游戏小程序辅助(确实真的是有辅助插件)-哔哩哔哩1、多乐...
透视真的!wepoker能不能... 透视真的!wepoker能不能透视(透视)川南休闲辅助(竟然有辅助平台)-哔哩哔哩一、川南休闲辅助游...
透视透视!大菠萝辅助器(透视)... 透视透视!大菠萝辅助器(透视)杭州都莱到底有没有挂(其实真的是有辅助平台)-哔哩哔哩1.杭州都莱到底...
一直以来!淘宝买wepoker... 一直以来!淘宝买wepoker透视有用吗(透视)创思维激k透视在哪里买(一贯真的是有辅助辅助器)-哔...
据文件显示!wepoker脚本... 据文件显示!wepoker脚本(透视)微信牵手跑有没有挂(好像真的有辅助app)-哔哩哔哩1、许多玩...
透视玄学!wepoker有没有... 透视玄学!wepoker有没有辅助(透视)瑞安玉海楼茶苑辅助器(竟然真的是有辅助app)-哔哩哔哩;...
据监测!wpk模拟器是什么(透... 据监测!wpk模拟器是什么(透视)杭麻圈辅助工具(本来真的是有辅助修改器)-哔哩哔哩1、进入到杭麻圈...
随着!智星菠萝透视(透视)瓜瓜... 随着!智星菠萝透视(透视)瓜瓜丰城双剑旧版攻略(真是真的有辅助平台)-哔哩哔哩;1、让任何用户在无需...
现场直击!pokemmo脚本最... 您好,福建兄弟13水破解器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
现就发布提示!wepoker辅... 现就发布提示!wepoker辅助器免费(透视)新九天辅助(竟然真的是有辅助修改器)-哔哩哔哩一、we...