首页 > 解决方案 > 预期验证器返回 Promise 或 Observable 异步验证器 FormGroup 角度 7

问题描述

希望你是安全的。我正在使用 anuglar 7,我正在通过 aysnc 验证 api 调用验证模板名称是否存在于 db 中。我将异步验证器作为第三个参数传递,但是当我在输入字段上输入内容时出现错误。谁能帮帮我。我搜索了很多帖子,但没有一个能帮助我。谢谢

问题 --> 当我输入一些值时,我得到“错误错误:预期的验证器返回 Promise 或 Observable。”

#下面是我的 create-table.component.ts 文件代码:

       ngOnInit() {
          this.getProducts();
   
    this.table = new FormGroup({

        tableName: new FormControl ('',
        Validators.required
        ,this.customTableNameValidator.bind(this)
         ),
    });
}

这是异步功能

                  customTableNameValidator() {
                    return (control: AbstractControl) => {
                     return this.dataService.templateDuplicate(control.value).pipe(
                         map((res) => {
                         console.log("result : ", res["message"]);
                         return res["message"] ? { templateExist: true } : null;
                      })
                    );
                  };
                 }

这是服务api调用代码。这里“res['message']”将返回布尔值

              templateDuplicate(tableName: string): Observable<any> {
                 return this.http
                     .post<any>(this.appBaseUrl + "validate-template-name/" + tableName, null)
                     .pipe(
                      map((res) => {
                      console.log("Res : ", res["message"]);
                       return res["message"];
                      })
                  );
               }

下面是 Html 文件元素标签

                 <input class="form-control" formControlName="tableName"  />

下面是 api 响应。我正在获取“消息”属性值并在上面的代码中返回它。

                  {
                    "statusMessage": null,
                    "filePath": null,
                    "message": true
                  }

标签: angular

解决方案


修改您的代码以查看它是否对您有帮助

  customTableNameValidator() {
    return (control: AbstractControl) => {
      return this.dataService.templateDuplicate(control.value).pipe(
        map((res:any) => {
          console.log("result : ", res["message"]);
          return res["message"] ? { templateExist: true } : null;
        })
      );
    };
  }
  ngOnInit() {
    this.table = new FormGroup({
      tableName: new FormControl ('',
       [ Validators.required, this.customTableNameValidator]
      ),
    });
  }

推荐阅读