1

I'm trying to add a new AsyncValidator to check whether user's email already exist in database. Below is may validator:

  export class UniqueEmailValidator implements AsyncValidator {
    constructor(private webService: WebWrapperService) {}

    validate(ctrl: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > {    
      return this.webService.isEmailExistEx(ctrl.value)
        .pipe(
          map(res => {    
            console.log("get response" + res);
            if (res) {
              return { 'uniqueEmail': true};
            }
            return null;                
          })

        );
    }
  }

The function isEmailExistEx in service will send a post request to server.

isEmailExistEx(email: string): Observable<boolean> {
    this.http.post(this.baseUrl + "auth/verify",
      {
        "email": email
      })
      .subscribe(
        (val: any) => {
          if (!val.result) {
            return of(false);
          } else {
            return of(true);
          }
        },
        response => {
          return of(false);
        },
        () => {
          return of(false);
        });
  }

It reports following error:

A function whose declared type is neither 'void' nor 'any' must return a value.

How should I modify this function?

1 Answer 1

1

You're subscribeing to the Observable which will consume the value wrapped in it.

Use map instead of subscribeing and return a boolean value from it::

isEmailExistEx(email: string): Observable<boolean> {
  return this.http.post(this.baseUrl + "auth/verify", { email })
  .pipe(
    map((val: any) => val.result ? true : false)
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.