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

相关内容

热门资讯

透视详细"wepok... 透视详细"wepoker怎么看牌型"确实有辅助攻略(哔哩哔哩)1、玩家可以在wepoker怎么看牌型...
透视有挂"hhpok... 透视有挂"hhpoker真的假的"总是真的是有辅助攻略(哔哩哔哩)1、玩家可以在hhpoker真的假...
透视解迷"德普之星私... 透视解迷"德普之星私人局辅助免费"果然是有辅助教程(哔哩哔哩)1、玩家可以在德普之星私人局辅助免费透...
透视有挂"wpk私人... 透视有挂"wpk私人局有透视吗"都是存在有辅助插件(哔哩哔哩)1、wpk私人局有透视吗有没有辅助教程...
透视透视"wepok... 透视透视"wepokerplus作必弊"真是是有辅助脚本(哔哩哔哩)1、wepokerplus作必弊...
透视曝光"wepok... 透视曝光"wepoker私人局规律"都是有辅助软件(哔哩哔哩)1、wepoker私人局规律透视辅助软...
透视分享"werpl... 透视分享"werplan有挂吗"原来有辅助神器(哔哩哔哩)该软件可以轻松地帮助玩家将werplan有...
透视推荐"hhpok... 透视推荐"hhpoker是真的吗"原来真的有辅助app(哔哩哔哩)1、下载好hhpoker是真的吗脚...
透视总结"约局吧德州... 透视总结"约局吧德州透视"好像真的是有辅助器(哔哩哔哩)1、下载好约局吧德州透视透视辅助下载之后点击...
透视分享"wepok... 透视分享"wepoker透视最简单三个步骤"一贯存在有辅助技巧(哔哩哔哩)一、wepoker透视最简...