Debouncing HTTP requests in Angular

The easiest way to accomplish what you're after is to set up a Subject (I'm assuming you have access to Rxjs here). Initialize one in your component:

inputSubject: Subject<string> = new Subject<string>();

Since a Subject is both an observer and an observable, you're going to want to set up a subscription to listen for changes. Here's where you can apply your debounce.

this.subscription = this.inputSubject.asObservable()
    .debounceTime(1000)
    .subscribe(x => this.filtersChanged.emit(this.filters));

Now, in your emitFilters() function instead of directly emitting, push the value onto the Subject.

this.inputSubject.next(newValue);

Don't forget to store your subscription as a member of your component class and dispose of it properly in your OnDestroy().

ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
}

Tags:

Angular