angular - 角度异步验证器去抖动输入
问题描述
我想为我的 Angular 表单组编写一个自定义异步验证器,该验证器用于检查 url 是否可访问。但是,如果我对从 AbstractControl 更改的值进行去抖动,则 Control 总是以某种方式无效。到目前为止,这是我的代码
export class UrlValidator {
static createValidator(http: HttpClient) {
return (control: AbstractControl) => {
const url = control.value;
return http.get(url).pipe(
throttleTime(1500),
catchError(err => {
console.log('err', err);
if (err.status && err.status === 200) return of(null);
return of({ input: 'urlError' });
})
);
};
}
}
debouncetime 调用目前没有做任何事情
提前致谢
解决方案
您可能必须在验证器之外进行反跳。如果输入源不断发射,验证器将被连续调用,在 http 调用后设置去抖动不会做任何事情。
export class UrlValidator {
static controlValue=new Subject()
static createValidator(http: HttpClient) {
UrlValiator.controlValue.next(control.value)
return (control: AbstractControl) => {
return controlValue.pipe(
debounceTime(1500),
switchMap(()=>http(url))
catchError(err => {
console.log('err', err);
if (err.status && err.status === 200) return of(null);
return of({ input: 'urlError' });
})
);
};
}
}
推荐阅读
- c - GCC 优化魔法
- c# - C# Entity Framework 代码首先无法将相关数据添加到对象列表中
- mysql - 任何自动化 mySQL 查询验证的好工具?
- html - 如何使一些图像显示在带有文本的 div 下?
- vmware-clarity - 如何使用清晰的库迁移到 Angular 10?
- python - 如何将多个 .pcd 文件组合成一个包含点云数据(python)的 .pcd 文件?
- r - 在 R 中计算月份数
- apollo-server - 如何在 React Relay 和 Apollo Server 中使用持久查询
- reactjs - 在 expo web 和 nextjs 中导入 expo 字体和资产
- robotframework - 使用 MockLab (wiremock) 通过 Robot Framework 进行测试时,“多部分请求正文不存在”