全局搜索 + 防抖 提升性能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
rxjs性能
我的對截流和防抖的理解:this
防抖:當連續操做中止的時間超過規定的等待時間後,回調函數纔會被調用。好比:中止輸入後一段時間,回調函數纔會觸發。spa
截流:在連續操做的這段時間內,回調函數在規定的時間段內纔會被調用。好比:連續拖拽,回調函數只會每一個一段時間觸發一次code