How to use debounce time for searching data in API's for keyup input change event. Give a look at the following code. It is not working. A search request to API is made on every input change. I want to make a search request to API using some denounce time.
Thank you in advance
.html
<input matInput (keyup) ="Onsearchinput($event.target.value)">
.ts
Onsearchinput(value){
debounceTime(500)
console.log(value)
this.productService.search_Products(value).subscribe(data => {
if(data){
console.log(data)
this.product_list = data
}
})
}
A form control will expose the changes in its values as an observable named valueChanges
. You're going to need to use the pipe
operator, piping valueChanges
into it. You can't just call debounceTime
like you are doing above.
You're also going to want to use something like a switchMap
to ensure that any in-flight requests are cancelled if a user types something while a request is in progress.
Without seeing your code this is the best I can really do.
Try using a formControl.
html;
<input matInput [formControl]='myControl'>
In your ts, declare this as a class variable:
myControl = new FormControl();
Then pipe the changes from it like this (can go in ngOnInit
):
this.myControl.valueChanges.pipe(
debounceTime(500),
switchMap(changedValue => this.productService.search_Products(changedValue)),
).subscribe(productList => this.product_list = productList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With