I want to add debounceTime
and distinctUntilChanged
in my async validator.
mockAsyncValidator(): AsyncValidatorFn {
return (control: FormControl): Observable<ValidationErrors | null> => {
return control.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(value => {
console.log(value); // log works here
return this.mockService.checkValue(value).pipe(response => {
console.log(response); // log did not work here
if (response) {
return { invalid: true };
}
return null;
})
})
);
}
The code above did not work, the form status becomes PENDING
.
But when I use timer
in this answer, the code works, but I can't use distinctUntilChanged
then.
return timer(500).pipe(
switchMap(() => {
return this.mockService.checkValue(control.value).pipe(response => {
console.log(response); // log works here
if (response) {
return { invalid: true };
}
return null;
})
})
);
I tried to use BehaviorSubject
like
debouncedSubject = new BehaviorSubject<string>('');
and use it in the AsyncValidatorFn
, but still not work, like this:
this.debouncedSubject.next(control.value);
return this.debouncedSubject.pipe(
debounceTime(500),
distinctUntilChanged(), // did not work
// I think maybe it's because of I next() the value
// immediately above
// but I don't know how to fix this
take(1), // have to add this, otherwise, the form is PENDING forever
// and this take(1) cannot add before debounceTime()
// otherwise debounceTime() won't work
switchMap(value => {
console.log(value); // log works here
return this.mockService.checkValue(control.value).pipe(response => {
console.log(response); // log works here
if (response) {
return { invalid: true };
}
return null;
}
);
})
);