Sharpeye500
Sharpeye500

Reputation: 9073

Avoiding duplicate calls inside keyup event in angular

What i am trying to do is

  1. call a service and bind the data on ngOnit()
  2. In the given textbox, when a user types something, instead of calling API call for every letter, wait for a second, if user doesn't type further, then make API call (need to debounce between user strokes).
  3. When the search is done, i want to bind that data back.

Issue: For the below API call, for the same search keyword 3 to 4 calls are made, i want to make 1 call instead, any help will be appreciated, thanks.

In my html file

<div *ngIf=let result in result$ | async>
  
</div>
<input type="text" (keyup)="filterData($event)">

In my component file

ngOnInit(){

this.result$ =  someServiceCall(); //result$ is an observable
}

filterData(event)
{
  fromEvent(event.target, 'keyup')
  .pipe(debounceTime(1000), distinctUntilChanged(),
  mergeMap((search) => {
    this.result$ = someServiceCall(event.target.value)
    }))
observable.subscribe(value) => {
})
}
return this.result$
}

Upvotes: 0

Views: 878

Answers (1)

Vuth
Vuth

Reputation: 21

What you did is create the observable multiple times as user input. You should create a subject like filterThrottle = new Subject<string>(); then subscribe it in ngOnInit like

this.filterThrottle.pipe(debounceTime(1000)).subscribe((input) => {
 // Do something with input
});

In html emit like this

<input type="text" (keyup)="filterThrottle.next($event)">

Upvotes: 1

Related Questions