Joseph Genchik
Joseph Genchik

Reputation: 1841

Angular 2 Using Observable.debounce() with Http.get

I understand that Observable.debounce() can be used to process rapid fire form input. As Http GET also returns an Observable, I wonder it it is possible to debounce rapid http requests? I tried debounceTime() but it did not appear to do anything.

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .map(r => r.json()) 
   .debounceTime(10000) 
  .catch(this.handleError); 
};

Upvotes: 10

Views: 23812

Answers (3)

Emir Mamashov
Emir Mamashov

Reputation: 1170

in Angular7:

import { Observable, of, timer } from 'rxjs';
import { catchError, retry, map, debounce } from 'rxjs/operators';

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .pipe(
      debounce(() => timer(10000)),
      catchError(this.handleError)
   );
};

Upvotes: 3

A. Morel
A. Morel

Reputation: 10344

You have to transform from subject observable into an http observable with switchMap like this:

observableObj$: Observable<any>;
subjectObj = new Subject();

 ngOnInit() {
    this.observableObj$ = this.subjectObj.pipe(
      debounceTime(1000),
      switchMap(() => {
        ...
        return this.http.get(some_url).map(r => r.json());
      }),
    );

    this.observableObj$.subscribe((data) => {
      // result of http get...
      ...
    });
}

getStuff() {
    this.subjectObj.next();
}

Upvotes: 4

Thierry Templier
Thierry Templier

Reputation: 202146

The debounceTime allows to buffer events and only handle the last one after an amount of time.

It's useful in the context of inputs but it should be defined on the observable that triggers the event not on the one created for the HTTP request.

Here is a example on a control associated with an input that leverages the debounceTime operator:

@Component({
  (...)
  template: `
    <input [ngFormControl]="ctrl"/>
  `
})
export class MyComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges
               .debounceTime(500)
               .distinctUntilChanged()
               .switchMap((value: string) => {
                 // Get data according to the filled value
                 return this.service.getData(entry);
               })
               .subscribe(data => {
                 // Update the linked list
                 this.list = data;
               });
  }
}

This article could also interest you:

Following the micronyks's comment, here is an additional link:

Upvotes: 12

Related Questions