Angular7里面实现 debounce search

项目需求:

  全局搜索 + 防抖 提升性能html

技术:

  [(ngModel)]  [(ngModelChange)]  Rxjs( Subject)api

代码展现: 

// html
<input type="text" placeholder="Search" [(ngModel)]="globalSearchContent" (ngModelChange)="globalSearch()">
// xx.component.ts
import { Observable, combineLatest, Subject } from 'rxjs';
import { distinctUntilChanged, debounceTime } from 'rxjs/operators';


private searchStream = new Subject<string>();

ngOnInit() {
// 订阅 this.initGlobalSearchSubscription(); } ngOnDestroy() {
// 取消订阅 this.searchStream.unsubscribe(); } private async initGlobalSearchSubscription() { this.projectId = await this.localStorageService.getItem('currentProject'); this.searchStream.pipe( debounceTime(400), distinctUntilChanged()) .subscribe(async(searchContent) => { const searchResult = await this.projectService.globalSearch(this.projectId, searchContent).toPromise(); this.searchMenuList = searchResult.body; }); } private globalSearch() {
  // 消息发送 this.searchStream.next(this.globalSearchContent); }

具体实例app

具备防抖和截流的第三方库:

lodashasync

underscore函数

rxjs性能

我的对截流和防抖的理解:this

防抖:当连续操做中止的时间超过规定的等待时间后,回调函数才会被调用。好比:中止输入后一段时间,回调函数才会触发。spa

截流:在连续操做的这段时间内,回调函数在规定的时间段内才会被调用。好比:连续拖拽,回调函数只会每一个一段时间触发一次code

相关文章
相关标签/搜索