javascript - 以 Angular 添加 AsyncValidator 时出错

标签 javascript angular

我正在尝试添加一个新的 AsyncValidator 来检查用户的电子邮件是否已存在于数据库中。 以下是可能的验证器:

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

        );
    }
  }

服务中的isEmailExistEx函数会向服务器发送一个post请求。

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

它报告以下错误:

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

这个函数应该怎么修改?

最佳答案

您正在订阅Observable,它将消耗包装在其中的值。

使用 map 而不是 subscribe 并从中返回一个 boolean 值::

isEmailExistEx(email: string): Observable<boolean> {
  return this.http.post(this.baseUrl + "auth/verify", { email })
  .pipe(
    map((val: any) => val.result ? true : false)
  );
}

关于javascript - 以 Angular 添加 AsyncValidator 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264824/

相关文章:

html - HTML 中的属性和特性有什么区别?

javascript - 如何使用 Nativescript 从链接获取 ID

Javascript 数学用逗号替换点/小数

javascript - 我们如何向使用 JavaScript 中的 document.createElement() 创建的元素添加焦点等事件?

javascript - 显示用户有多少 Facebook 通知的 PHP 应用程序

javascript - 删除 Firebase 中的对象? (JavaScript)

html - 如何使用 Javascript 对象中的变量值动态更改按钮的颜色?

Angular 5 - 如何生成定义文件

具有动态名称的 Angular Material 2 Datepicker

javascript - 当有人使用 javascript 或 jquery 粘贴文本时,如何仅禁用/删除输入字段内文本开头的空格?