Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 use debounceTime on method

Tags:

angular

rxjs

I'm trying to use debounceTime on an Angular 5 function but I'm not sure how to use it. When I built a search function I could use it, because it was bind to the changes made on that input value, like this:

this.search
    .debounceTime(400)
    .distinctUntilChanged()
    .takeUntil(this.onDestroy)
    .subscribe((model) => {
        return this.filterArray(model);
    });

But now I want to apply it to a function, this function is called from many places, and send an event to the database via http post, something like this:

private saveData(): void {
    this.http.post('event/url', data).takeUntil(this.onDestroy).subscribe((response: Response) => {
        // -
    }, error => {
        // -
    });
}

Is there a way to do it like saveData().debounceTime() Or do I need to do it other way?

like image 900
celsomtrindade Avatar asked Jan 03 '23 16:01

celsomtrindade


1 Answers

I'm not sure but something like this might work:

$save: Subject<void> = new Subject<void>();

In your constructor or init:

this.$save
  .debounceTime(400)
  .switchMap(() => this.http.post(...post params))
  .subscribe(..Do something);

Your save method:

saveData(){
    this.$save.next();
}
like image 94
Robin Dijkhof Avatar answered Jan 19 '23 10:01

Robin Dijkhof