How to implement a debounce time in keyup event in Angular 6
In the component you can do somthing like this. Create RxJS Subject
, In search
method which is called on keyup
event, do .next()
on this Subject
you have created. Then subscribe
in ngOnInit()
will debounce
for 1 second, as in below code.
searchTextChanged = new Subject<string>();
constructor(private http:Http) {
}
ngOnInit(): void {
this.subscription = this.searchTextChanged
.debounceTime(1000)
.distinctUntilChanged()
.mergeMap(search => this.getValues())
.subscribe(() => { });
}
getValues() {
return this.http.get("https://www.example.com/search/?q="+this.q)
.map(
(res:Response) => {
const studentResult = res.json();
console.log(studentResult);
if(studentResult.success) {
this.results = studentResult.data;
} else {
this.results = [];
}
}
)
}
search($event) {
this.searchTextChanged.next($event.target.value);
}
rxjs v6 has several breaking changes including simplifying import points for operators. Try installing rxjs-compat
, which adds back those import paths until the code has been migrated.
Import the necessary operators from RxJS
. Below ones are for RxJS 5.x
import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/debounceTime";
import "rxjs/add/operator/distinctUntilChanged";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/mergeMap";
For anyone coming across this in a newer version of angular (and rxjs).
The new Rxjs has pipeable operators and they can be used like this (from the accepted answers code)
ngOnInit() {
this.subscription = this.searchTextChanged.pipe(
debounceTime(1000),
distinctUntilChanged(),
mergeMap(search => this.getValues())
).subscribe((res) => {
console.log(res);
});