Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 InputFormControl and ValueChange fires continuously

I have a simple case where input is detected from an input field. when the value changes on the input, and after a short debounce time, a service is called which makes a http call and some data is returned.

However, instead of only firing once or twice, the service is calling the api between 16-30 times - even if the input is only 4 characters and therefore should fire 4 times.

My suspicioun is this may be to do with callbacks, or that I am implementing the valueChanges method incorrectly. In any case i have attached some code for review and would appreciate any feedback any input as I am new to angular and cannot see any error in implementation.

inputChange(input) {
    this.inputFormControl.valueChanges
        .debounceTime(5000)
        .distinctUntilChanged()
        .switchMap(input => this.userService.search(input))
        .subscribe(data => {
            this.data = data;
        },
    );
}
like image 607
zo0 Avatar asked Nov 25 '25 17:11

zo0


1 Answers

You are calling a method inputChange(input) when the value changes (assumingly) and your are also subscribing to valueChanges. Drop the inputChange method, and just use valueChanges:

constructor() {
  this.inputFormControl.valueChanges
    .debounceTime(5000)
    .distinctUntilChanged()
    .switchMap(input => this.userService.search(input))
    .subscribe(data => {
        this.data = data;
    }); 
}

Also remember to unsubscribe when component is destroyed!

like image 51
AT82 Avatar answered Nov 28 '25 15:11

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!