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

可紊 提交于 2019-12-29 08:41:16

问题


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

回答1:


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:

  • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html (see section "Linking with user events")

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

  • Everything is a stream: http://slides.com/robwormald/everything-is-a-stream (youtube: https://www.youtube.com/watch?v=UHI0AzD_WfY)



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/35991867/angular-2-using-observable-debounce-with-http-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!