场景:
监听输入变化从而触发搜索方法或某个方法的搜索框、输入框等
// 引入rxjs等包
import { Subject } from 'rxjs';
import { distinctUntilChanged, debounceTime } from 'rxjs/operators';
举例:
search()方法 会调用getList()这个方法向后台查询数据
// 预置方法
/*
调用后台查询数据接口
*/
getList(){
***
***
}
// 未添加防抖前,每次调用search()都会调用getList()
search(){
this.getList();
}
//添加防抖后,调用search()后,每300ms才会调用一次getList()
private inputStream = new Subject<string>();
ngOnInit() {
this.inputStream.pipe(debounceTime(300), distinctUntilChanged()).subscribe(() =>
this.getList());
}
search(){
this.inputStream.next()
}