1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular Asyncvalidator Error : 'Observable<Object>' is not assignable to type...

Discussão em 'Angular' iniciado por Heemanshu Bhalla, Maio 30, 2025.

  1. 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)
    );
    }
    }

    Continue reading...

Compartilhe esta Página