I'm getting below error in service.ts file i am trying to use Angular async validator ( Not Asyncvalidatefn ) that shoots on username text field on component but i am getting compile error on below line
return this.validateUserName(control.value).pipe(
Error:
Type 'Observable<{ userNameNotAvailable: boolean; } | null>' is not assignable to type 'Observable<ValidationErrors>'.
Type '{ userNameNotAvailable: boolean; } | null' is not assignable to type 'ValidationErrors'.
Service.ts Code
export class UserNameValidationService implements AsyncValidator {
constructor() { }
validate(control: AbstractControl): Observable<ValidationErrors> {
return this.validateUserName(control.value).pipe(
map((duplicateUserAvailable) => {
if (duplicateUserAvailable) {
return { userNameNotAvailable: true };
} else {
return null;
}
}),
catchError(() => of(null))
);
}
/* A static array is used to validate the availability of user names.
* Ideally it should be a service call to the server to search the value from a database.
*/
private validateUserName(username: string): Observable<boolean> {
const UserList = ["ankit", "admin", "user", "superuser"];
return of(UserList.includes(username.toLocaleLowerCase())).pipe(
delay(1000)
);
}
}
The definition of ValidatiorErrors
export type ValidationErrors = {
[key: string]: any;
};
Doesn't accept null
.
You need to return Observable<ValidationErrors | null>