I am using angular reactive form in my application. And when user type URL in text box, I am sending ajax request to server.
this.myForm.valueChanges.subscribe(form => {
if (this.myForm.valid) {
// call ajax for this.myForm.value.url
}
}
But when I type the letters in order "h", "ht", "http",
the request is sending immediately. I want to send request after I complete the type. So I think need a pipe for wait, but which?
You can use the debounceTime
rxjs operator (with a millisecond parameter):
import {debounceTime} from "rxjs/operators";
this.form.valueChanges.pipe(
debounceTime(1000)
).subscribe(...)
If you want to go further and avoid doing 2 subscriptions (for the form and the api call), you can use switchMap
rxjs operator :
import {debounceTime, switchMap} from "rxjs/operators";
this.form.valueChanges.pipe(
debounceTime(1000),
switchMap(value => {
if (this.form.valid) {
return this.api.save(value.url)
}
})
).subscribe(// return the result of the api call)
This is what you need with the condition :
Example:
import {debounceTime} from "rxjs/operators";
this.myForm.valueChanges.pipe(
this.myForm.valid,
debounceTime(1000))
).subscribe(res => this.data = res);
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.