简体   繁体   English

角度异步验证器去抖动输入

[英]Angular async Validator debounce input

I want to write a custom async Validator for my angular form group, which jop is to check if the url is reachable. 我想为我的角形表组编写一个自定义异步验证器,jop用于检查url是否可访问。 But if i debounce the value changed from the AbstractControl the Control is always invalid somehow. 但是如果我从AbstractControl中去掉了更改的值,那么Control在某种程度上总是无效的。 This is my code so far 到目前为止这是我的代码

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' });
            })
        );
    };
}
}

the debouncetime call doesn't do anything at the moment debouncetime调用此刻没有任何作用

thanks in advance 提前致谢

Your probably have to debounce outside of validator. 你可能不得不在验证器之外去抖。 Validator will get called continuously if the input source is keep emitting, putting debounce after http call doesn't do anything. 如果输入源持续发光,验证器将被连续调用,在http调用不执行任何操作后放置debounce。

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' });
            })
        );
    };
}
}

Okay the problem was, the Observable was stuck in the pending state. 好的问题是,Observable陷入了待决状态。 adding a .first() to the http observable did the trick 向http observable添加.first()可以达到目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM