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.

1 Answer 1

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); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer. OP you might wanna check this out 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.