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

Viewed 20650

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); 
};
3 Answers

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();
}

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)
   );
};
Related