【angular7】防抖、節流


...
import { Subject } from 'rxjs';
import { tap, catchError, debounceTime, distinctUntilChanged } from 'rxjs/operators';

...

export class demoComponent implements OnInit {
    //狀態
    codeSearch: boolean = false;

    searchText: Subject<string> = new Subject<string>();
  // 事件調用
    searchCode(keyword: string): any {
        this.searchText.next(keyword);
    }
  //調用接口獲取數據
    getCode(keyword: string): any {
        if (keyword === '') return;
        this.codeSearch = true;
        this.http.get(ApiUrl)
            .pipe(tap(() => {this.codeSearch = false;}))
            .subscribe((res: any) => {
                console.log(res)
                if (res.code == 200) {
                    this.strategyList = res.data;
                    this.cdr.detectChanges();
                    if (res.data.length == 0) {
                        this.msg.error('未查詢到');
                    }
                } else {
                    this.msg.error('獲取數據出錯');
                }
            });
    }

    constructor() { }

    ngOnInit() {
        this.searchText
            .pipe(debounceTime(300))
            .pipe(distinctUntilChanged())
            .subscribe(string => {
                this.getCode(string);
            });
    }
}

  


免責聲明!

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



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