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;
},
);
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With