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、玩家可以在hhpoke...
目前来看!德扑HHpoker有... 目前来看!德扑HHpoker有挂吗(透视)一贯存在有辅助安装(揭秘有挂)-哔哩哔哩德扑HHpoker...
透视黑科技!有哪些免费的wpk... 透视黑科技!有哪些免费的wpk作必弊码(透视)好像真的有辅助辅助器(有挂攻略)-哔哩哔哩1、进入游戏...
透视透视!hhpoker德州机... 透视透视!hhpoker德州机器人(透视)原来是有辅助神器(揭秘有挂)-哔哩哔哩所有人都在同一条线上...
透视好友房!aa poker透... 透视好友房!aa poker透视软件(透视)一直真的有辅助插件(有挂详细)-哔哩哔哩aa poker...
据通报!红龙poker辅助(透... 据通报!红龙poker辅助(透视)真是真的有辅助工具(有挂分析)-哔哩哔哩1、点击下载安装,红龙po...
透视系统!wpk透视辅助靠谱吗... 透视系统!wpk透视辅助靠谱吗(透视)其实存在有辅助插件(有挂方略)-哔哩哔哩1、上手简单,内置详细...
透视脚本!hhpoker有没有... 透视脚本!hhpoker有没有作必弊辅助(透视)原来存在有辅助辅助器(有挂透明挂)-哔哩哔哩1、很好...
透视安卓版!wpk软件是真的吗... 透视安卓版!wpk软件是真的吗(透视)竟然真的有辅助软件(有挂解惑)-哔哩哔哩一、wpk软件是真的吗...
刚刚!wpk透视是真的假的(透... 刚刚!wpk透视是真的假的(透视)本来真的是有辅助平台(有挂解惑)-哔哩哔哩1、每一步都需要思考,不...