Can't make debounceTime() or throttleTime() to work on an Angular http request

半城伤御伤魂 提交于 2020-04-10 09:09:02

问题


For the life of me, I can not make this work. I've searched and searched, but I couldn't find any example (all examples out there are with .fromEvent(), none on a http.get).

In my template, I have this input:

<input type="text" (input)="categoriesSearch($event)">

In my component, I have the following:

categoriesSearch(event) {
    this.categoriesSubscription = this.apiService
        .getCategoriesList(this.uploadForm.get('categories').value)
        .debounceTime(3000)
        // .throttleTime(3000)
        .subscribe(
            (response) => {
                this.categories = response.data;
            }
        );
}

And this is the method in my ApiService:

getCategoriesList(keyword = null) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Bearer', this.authService.user.token);

    const getParams: URLSearchParams = new URLSearchParams();
    getParams.set('keyword', keyword);
    return this.http.get(this.apiHost + '/categories', { headers: headers, search: getParams })
        .map(response => response.json());
}

In the categoriesSearch() method, I've tried both debounceTime() and throttleTime() (I also imported them, of course import 'rxjs/add/operator/debounceTime', import 'rxjs/add/operator/throttleTime').

But the http.get request is not debounced or throttled at all! If I type 10 characters in 3 seconds, it makes 10 http requests.

How on earth do I tell this.http.get to only make a request if at least 3 seconds have passed since the previous request or since 'no request' (meaning an initial 3 seconds delay)? Ok, maybe here I should say "since I've last typed something in my input".

I've also tried using debounceTime()/throttleTime() in the service directly, before the .map() operator - but the result is the same.


回答1:


But the http.get request is not debounced or throttled at all! If I type 10 characters in 3 seconds, it makes 10 http requests.

your implementing in a wrong way. you need capture input first, apply denounce and do HTTP request.

you can implement in several ways

1) Observable.fromEvent

 <input type="text" #input>

Component

 @ViewChild('input') text: ElementRef;

  ngAfterViewInit() {
    let text$ = Observable.fromEvent(this.text.nativeElement, 'keyup')
     .do(() => console.log("keyup"))
    .debounceTime(3000)
     .distinctUntilChanged()
    .switchMap(() => getCategoriesList())
        .subscribe(res => console.log(res));
  }

2) Using subject

<input type="text" (keyup)="search($event)">

component

  searchTerms = new Subject<string>();

search(term: string): void {
    this.searchTerms.next(term);
  }

ngOnInit(): void {

    this.searchTerms
      .debounceTime(3000)
      .distinctUntilChanged()
      .switchMap(() => getCategoriesList())
      .subscribe(term => { 
       console.log();
     });

3) Using form control

 <input type="text" [formControl]="term">

component

  term = new FormControl();

  ngOnInit() {
    this.items = this.term.valueChanges
                 .debounceTime(3000)
                 .distinctUntilChanged()
                 .switchMap(term => getCategoriesList(term))
                 .subscribe(res => console.log(res));
  }



回答2:


Using form control

 <input type="text" [formControl]="term">

component

term = new FormControl();

  ngOnInit() {
    this.items = this.term.valueChanges
                 .debounceTime(3000)
                 .distinctUntilChanged()
                 .switchMap(term => getCategoriesList(term))
                 .subscribe(res => console.log(res));
  }


来源:https://stackoverflow.com/questions/44183519/cant-make-debouncetime-or-throttletime-to-work-on-an-angular-http-request

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