简体   繁体   中英

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. But if i debounce the value changed from the AbstractControl the Control is always invalid somehow. 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

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.

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. adding a .first() to the http observable did the trick

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.

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