項目需求:
全局搜索 + 防抖 提高性能
技術:
[(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); }
具有防抖和截流的第三方庫:
個人對截流和防抖的理解:
防抖:當連續操作停止的時間超過規定的等待時間后,回調函數才會被調用。比如:停止輸入后一段時間,回調函數才會觸發。
截流:在連續操作的這段時間內,回調函數在規定的時間段內才會被調用。比如:連續拖拽,回調函數只會每個一段時間觸發一次