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

相关内容

热门资讯

7分钟下载!微乐小程序黑科技,... 7分钟下载!微乐小程序黑科技,微乐小程序自建房辅助器下载(开挂)本来真的有挂(2026)1、不需要A...
据监测!微乐小程序免费黑科技,... 据监测!微乐小程序免费黑科技,微乐小程序辅助脚本平台(透视)原来是有挂(哔哩哔哩)1、让任何用户在无...
1分钟开挂!微乐小程序免费黑科... 1分钟开挂!微乐小程序免费黑科技,微乐脚本(开挂)竟然存在有挂(2026)微乐小程序免费黑科技能透视...
2026版教程!微乐小程序免费... 2026版教程!微乐小程序免费黑科技,微信小程序微乐辅助器免费版v2.0(透视)切实存在有挂(哔哩哔...
7分钟神器!微乐小程序黑科技,... 7分钟神器!微乐小程序黑科技,微乐小程序脚本(开挂)真是有挂(2026)1、微乐小程序黑科技脚本辅助...
透视软件!微乐小程序免费黑科技... 透视软件!微乐小程序免费黑科技,微信小程序微乐跑得快技巧(透视)切实是有挂(哔哩哔哩)微信小程序微乐...
4分钟教程!微乐小程序黑科技,... 4分钟教程!微乐小程序黑科技,微信小程序透视微乐(开挂)真是真的有挂(2026)在进入微乐小程序黑科...
受玩家影响!微乐小程序黑科技,... 受玩家影响!微乐小程序黑科技,微信小程序微乐破解器2025(透视)一直有挂(哔哩哔哩)1、下载好微信...
一分钟插件!微乐小程序免费黑科... 一分钟插件!微乐小程序免费黑科技,微乐自建房透视(开挂)真是真的有挂(2026)1、微乐小程序免费黑...
教程辅助挂!微乐小程序黑科技,... 教程辅助挂!微乐小程序黑科技,手机微乐小程序破解器(透视)竟然是有挂(哔哩哔哩)1、下载好手机微乐小...