0

I'm making a search field. Before making the API call I want to wait for 2 seconds after the user has finished typing. Here is my code:

HTML:

<input type="text" pInputText (input)="onInput()" [(ngModel)]="value1" placeholder="Search">

TS:

searchTerm : Subscription;
onInput() {
    this.searchTerm = from(this.value1);
    this.searchTerm
      .pipe(
        map((event: any) => this.value1),
        debounceTime(2000),
        distinctUntilChanged()
      )
      .subscribe((res: any) => {
        console.log(res);
      });
  }

My code is not waiting for 2 secs. The console log is happening immediately. Please correct my mistake.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110

1 Answers1

1

I think using a subject will be a better way to achieve what you want

searchTerm: Subject<any> = new Subject();

ngOnInit(){
  this.searchTerm
    .pipe(
      map((event: any) => this.value1),
      debounceTime(2000),
      distinctUntilChanged()
    )
    .subscribe((res: any) => {
      console.log(res);
    });
}

onInput() {
  this.searchTerm.next(this.value1); 
}
Mr. Stash
  • 2,940
  • 3
  • 10
  • 24
  • 2
    This is the answer. OP you might wanna check this out https://stackoverflow.com/a/54162061/3486691 for more explanation - you are recreating your obs. chain so there is nothing to debounce every time you cann your function. – ForestG Nov 21 '22 at 10:36