I just updated angular in ionic app from version 4 to 5. I have some search FormControl inputs that allow user to search a database via ajax requests. I used debounceTime() method to delay ajax search request but after angular upgrade this method is no longer available. I removed this method call but now a new request is made on every user key press on android.
Is there any other way to achieve this delay?
this.searchControl.valueChanges
.debounceTime(2000)
.subscribe(search => this.getCities(search));
Just like you can see in Ionic docs:
RXJS 5.5.2 Updates
The recent update of RXJS includes a change in how operators are applied.
Traditionally, operators were applied like this:
import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/switchMap'; export MyClass { someMethod(){ // Using Reactive Forms this.input.valueChanges .debounceTime(500) .switchMap(inputVal => this.service.get(inputVal)) .subscribe(res => console.log(res)) } }
This approach involved modifying the Observable prototype and patching on the methods.
RXJS 5.5 introduces a different way to do this that can lead to significantly smaller code bundles, lettable operators.
To use lettable operators, modify the code from above to look like this:
// Use Deep imports here for smallest bunlde size import { debounceTime } from 'rxjs/operators/debounceTime'; import { switch } from 'rxjs/operators/switchMap'; // <- Please read the update! export MyClass { someMethod(){ // Using Reactive Forms // We use the new `.pipe` method on the observable // too apply operators now this.input.valueChanges .pipe( debounceTime(500), switchMap(inputVal => this.service.get(inputVal)) ) .subscribe(res => console.log(res)) } }
This slight change allows only import the operators we need in our code. This will result in a smaller, faster application. This example uses Deep Imports, which allow the module we want to import to be isolated.
So basically you'd need to slightly change the import statement to use deep imports
import { debounceTime } from 'rxjs/operators/debounceTime';
And then use the debounceTime
inside of the pipe(...)
method:
this.input.valueChanges
.pipe(
debounceTime(500),
// you can chain more operators if needed ...
// ...
)
.subscribe(res => console.log(res))
You can still use the old way (since this is not a breaking change yet) but using lettable operators will result in a smaller, faster application.
UPDATE
Just like @lifetimes mentioned in his comment (and as you can see here), this import
import { switch } from 'rxjs/operators/switchMap';
should be replaced by
import { switchMap } from 'rxjs/operators/switchMap';
when using newer versions.
May be help this example:
let debounce = this.name.valueChanges.pipe(
debounceTime(1000), // delay 1000 msec
distinctUntilChanged() // only for changed value
);
debounce.subscribe(changes => {
console.log(changes);
});
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