我有一个搜索框,我想在用户结束输入几秒钟后输入一个单词后向服务器发送请求。如何将debouncetime()应用于服务?
这是我的代码:
myComponent.html
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
myComponent.ts
applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.scanService.getFilteringScans(filterValue).subscribe(response => {
this.scans = response.results;
this.next = response.next;
this.previous = response.previous;
this.scans_length = response.count;
this.dataSource = new MatTableDataSource(this.scans.map(function(obj){return new ScanDetails(obj)}));
});
this.dataSource.filter = filterValue;
}
myService.ts
getFilteringScans(param): Observable<ScanList> {
return this.http.get<ScanList>(this.scansUrl + '?search=' + param).pipe(
map(response => response),
catchError(this.handleError)
);
}
有人可以帮我吗?
答案 0 :(得分:0)
由于您正在使用Angular,因此实际上可以使用RxJS的debounceTime运算符。
import { debounceTime, map, switchMap } from 'rxjs/operators';
import { Subject } from 'rxjs';
.
.
onChange = new Subject<string>();
ngOnInit() {
this.subscription = this.onChange
.pipe(
debounceTime(1000),
switchMap(search => this.applyFilter(search)),
).subscribe();
}
applyFilter(value) {
this.onChange.next(value);
}