[英]How to wait Angular reactive form until text complete?
我在我的应用程序中使用角反应形式。 当用户在文本框中键入 URL 时,我将向服务器发送 ajax 请求。
this.myForm.valueChanges.subscribe(form => {
if (this.myForm.valid) {
// call ajax for this.myForm.value.url
}
}
但是当我按"h", "ht", "http",
顺序输入字母时"h", "ht", "http",
请求会立即发送。 我想在完成类型后发送请求。 所以我认为需要一个管道等待,但是哪个?
您可以使用debounceTime
rxjs运营商(以毫秒参数):
import {debounceTime} from "rxjs/operators";
this.form.valueChanges.pipe(
debounceTime(1000)
).subscribe(...)
如果您想更进一步并避免进行 2 个订阅(对于表单和 api 调用),您可以使用switchMap
rxjs 运算符:
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)
这是您需要的条件:
例子:
import {debounceTime} from "rxjs/operators";
this.myForm.valueChanges.pipe(
this.myForm.valid,
debounceTime(1000))
).subscribe(res => this.data = res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.