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

相关内容

热门资讯

据公告内容"wepo... 据公告内容"wepoker代打辅助"大菠萝免费辅助(本来真的是有辅助软件)-哔哩哔哩1、进入游戏-大...
透视代打"wepok... 透视代打"wepokerplus脚本"hhpoker真能买到挂吗(一贯是真的辅助安装)-哔哩哔哩1、...
据公告内容"wepo... 据公告内容"wepoker透视是真的吗"aapoker辅助软件合法吗(一直真的是有辅助修改器)-哔哩...
透视模拟器"wepo... 透视模拟器"wepoker新号好一点吗"wepoker有用吗(切实有辅助app)-哔哩哔哩1、wep...
于此同时"hhpok... 于此同时"hhpoker有后台操作吗"poker world辅助器(其实真的是有辅助插件)-哔哩哔哩...
据权威媒体报道"we... 据权威媒体报道"wepoker线上大神"wepoker破解是真的还是假的(一贯真的是有辅助app)-...
值得注意的是"aap... 值得注意的是"aapoker安装包怎么使用"wpk俱乐部辅助器(真是是有辅助辅助器)-哔哩哔哩1、下...
透视教程"德扑圈透视... 透视教程"德扑圈透视挂"约局吧app有挂吗(切实真的有辅助安装)-哔哩哔哩1、下载好约局吧app有挂...
此事引发广泛关注"w... 您好,拱趴大菠萝十三水作必弊这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
透视工具"wepok... 透视工具"wepoker有没有挂"sohoopoker辅助(其实是真的辅助工具)-哔哩哔哩1、下载好...