首页 > 解决方案 > 角度异步验证器去抖动输入

问题描述

我想为我的 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 调用目前没有做任何事情

提前致谢

标签: angularformsvalidationrxjsobservable

解决方案


您可能必须在验证器之外进行反跳。如果输入源不断发射,验证器将被连续调用,在 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' });
            })
        );
    };
}
}

推荐阅读