4

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
        }
      })
  }
pratik jaiswal
  • 1,855
  • 9
  • 27
  • 59
  • 1
    Have you even tried to search for this? https://stackoverflow.com/a/40777621/3375906 – trungk18 Apr 30 '20 at 08:17
  • The problem is I am using this inside formArray. So I can't write code in constructor or ngOninit or ngAfterviewinit. And If I use debounce time in keyup event, search operation is occuring for every input change – pratik jaiswal Apr 30 '20 at 08:25
  • Then you show the complete code for the formArray. Otherwise, we won't know what is your difficulty. – trungk18 Apr 30 '20 at 09:18
  • it's relationed with this post? https://stackoverflow.com/questions/61503425/angular-9-formarray-search-operation-executing-for-only-first-dynamic-control/61519813#61519813 – Eliseo Apr 30 '20 at 09:45

1 Answers1

8

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);
deaks
  • 305
  • 2
  • 8