简体   繁体   中英

Angular2 No Http request in a time interval

I'm new to angular 2. I have a value binded to user interaction and i need to send this value over http requests. I have an event fired when value changed, but the value can change multiple times per second. I want to limit the http requests: 1 per 2 seconds when user interact. I don't want to send http request when no interaction. So i wanted to do it with timer or interval but i don't know the angular2 way for this:

onChange() {

  if(_interval.timerFinished) {
      http.get(.............);
      _interval.launchTimer(2000); //2 seconds
  }

}

Maybe using this: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/interval.md

how about debounce

You can try Sample or ThrottleFirst as well.

http://reactivex.io/documentation/operators/sample.html

http.get(.............).debounce(2000)

I want to limit the http requests

In order to do so, you can bind the element by adding in the html element:

[(ngModel)] = "searchQuery" [ngFormControl]="searchQueryControl"

And then in your code:

// Remember to import these things:
import {FORM_DIRECTIVES, Control} from 'angular2/common';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

constructor ( ... ) {
    //...
    this.searchQuery = '';
    this.searchQueryControl = new Control();
    //...

    this.searchQueryControl
        .valueChanges
        .debounceTime(1000)
        .distinctUntilChanged()
        .subscribe(text => {

            if(text !== '') {
              this.searchQuery = text;

              // Do whatever you want with the text
            }
      });

    //...
}

By doing that, we would only run the code when the input has changed ( this.searchQueryControl.valueChanges ), and when there hasn't been another change within 1 second ( .debounceTime(1000) ). The distinctUntilChanged() allow us to run the code if the value is different to the last time it ran. So if the user typed 'asd', hit the backspace key and then retyped the ending 'd' again, nothing would happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM