【问题标题】:Angular Custom Validators. How to validate a form field using a given Promise?Angular 自定义验证器。如何使用给定的 Promise 验证表单字段?
【发布时间】:2023-04-03 07:25:01
【问题描述】:

我需要使用返回 Promise 的方法来验证表单字段。但它永远不会返回错误,因为 Promise 是异步的。

这是我的验证器:

static email(usersService: UsersService): ValidatorFn {

  return (control: AbstractControl):{ [key: string]: boolean | null } => {
    const email = control.value;
    if (email) {
      usersService.validateUsername(email).then(
        (result) => { return result.username ? {emailExists: true} : null }
      )
    } else {
      return null;
    }
  }}

这是我的 UsersService 方法

validateUsername(username: string): Promise<{"username": string}> {
  return this.httpClient.post('/users/username_validation', {"username": username}).pipe(
    map((body: {"username": string}) => body),
  ).toPromise()}

【问题讨论】:

  • 你看过AsyncValidatorFn吗?
  • @KurtHamilton 我看过了。还是一样的问题
  • AsyncValidatorFn - 顾名思义 - 旨在进行异步验证。您能否发布您使用它的尝试,以便我们了解它为什么不适合您。
  • 我尝试了与我发布的相同的方法,只是更改了返回类型

标签: angular typescript promise customvalidator


【解决方案1】:

我认为你错过了 return 的承诺,这应该可行

if (email) {
  return usersService.validateUsername(email).then( // here in this line
    (result) => { return result.username ? {emailExists: true} : null }
  )
}

你可以将它重构为

 return (control: AbstractControl):Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => 
 {
  const email = control.value;
  return (email &&  usersService.validateUsername(email).then( 
    (result) => { return result.username ? {emailExists: true} : null }
  )) || null;
 }

【讨论】:

  • 还是同样的问题
【解决方案2】:

我需要做的就是像这样使用 AsyncValidator:

validator.ts

import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidator, ValidationErrors } from '@angular/forms';
import { Observable} from 'rxjs';

import { UsersService } from "@app/users/users.service";


@Injectable({
  providedIn: 'root'
})

export class EmailValidator implements AsyncValidator {

  constructor( private usersService: UsersService ) { }

  validate( control: AbstractControl): Promise<ValidationErrors> | Observable<ValidationErrors> {

    const email = control.value;
    if (email) {
      return this.usersService.validateUsername(email).then(
        (result) => { 
          console.log(result)
          return result.username ? {emailExists: true} : null 
        }
      )
    } else {
      return null;
    }

  }
}

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2019-01-07
    • 2019-03-15
    相关资源
    最近更新 更多