Angular7里面實現 debounce search


項目需求:

  全局搜索 + 防抖 提高性能

技術:

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

代碼展示: 

// 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); }

具體實例

具有防抖和截流的第三方庫:

lodash

underscore

rxjs

個人對截流和防抖的理解:

防抖:當連續操作停止的時間超過規定的等待時間后,回調函數才會被調用。比如:停止輸入后一段時間,回調函數才會觸發。

截流:在連續操作的這段時間內,回調函數在規定的時間段內才會被調用。比如:連續拖拽,回調函數只會每個一段時間觸發一次


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM