To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a specific interval.
However, I encountered an issue when adding switchMap to the code - the callback of switchMap is not being invoked.
Here is the original working code without switchMap:
public static createUniqueFieldValidator(
target: 'username' | 'email' | 'phone',
checker: (value: string) => boolean,
userService: UserService
): AsyncValidatorFn {
return (control: AbstractControl): Observable<NullableType<ValidationErrors>> => {
if (!!control.value && checker(control.value)) {
return fromPromise<SomeReturnedType>(
userService.checkUnique({ [ target ]: control.value })
).pipe<NullableType<ValidationErrors>>(.......);
}
return of<null>(null);
};
}
The issue arises when switchMap is added:
public static createUniqueFieldValidator(
target: 'username' | 'email' | 'phone',
checker: (value: string) => boolean,
userService: UserService
): AsyncValidatorFn {
return (control: AbstractControl): Observable<NullableType<ValidationErrors>> => {
if (!!control.value && checker(control.value)) {
// We do get here, I've checked
return timer(300).pipe<NullableType<ValidationErrors>>(
switchMap<number, Observable<NullableType<ValidationErrors>>>(
(): Observable<NullableType<ValidationErrors>> => {
console.log('SwitchMap');// The whole callback is never called
// Here I'm supposed to make an HTTP request instead of returning a null
return of<null>(null);
}
)
);
}
return of<null>(null);
};
}
Attempts to fix the issue like using of
and rearranging methods did not work as expected.