首页 > 解决方案 > 如何将函数转换为 Angular8 中表单控件的异步验证器?

问题描述

我有一个日期类型的表单控件,允许用户选择一个日期。我想创建一个异步验证器来检查提交的日期是否在我的数据库中已经存在 x 次。如果是这样,请提供以下错误:

order.get('DateOfDelivery').errors?.exists

我在我的类商店组件中创建了这个函数(它对我的数据库起作用。它在查询日期返回适当数量的订单):

  checkDeliveriesDate(event) {
    console.log(event.target.value);
    let date = { date: event.target.value };
    this.SS.getOrdersPerDate(date).subscribe(
      res => {
        console.log(res);
        /*
        if (res.length>3){
          formcontrol for e should turn invalid 
        }
        else{
          valid
        }
        */
      },
      err => {
        console.log(err);
      }
    )
  }

这是表单控件。我知道异步验证器需要成为第三个参数-

DateOfDelivery: new FormControl('', Validators.required),/*AsyncValidatorHere*/),

这是HTML-

<input type="date" class="form-control" formControlName="DateOfDelivery" (change)='checkDeliveriesDate($event)'>

我很感激帮助。先感谢您

编辑:

checkDeliveriesDateValidator(ctrl: AbstractControl) {

  if (!ctrl || String(ctrl.value).length === 0) {
    console.log("!c|| String (c.value).length ===0")
    return null;

  }

  return (ctrl && ctrl.value) ? this.SS.getOrdersPerDate({ date: ctrl.value }).pipe(
    map(res => {
      let deliveriesDate:any=res;
      console.log(deliveriesDate);
      if (deliveriesDate.length>3){ 
        return {exists: true};
      }
      else{
        return null;
      }
    })
  ) : null;
}

异步验证器正在产生此错误-

错误类型错误:无法读取未定义的属性“SS”

标签: angularangular-forms

解决方案


you return the observable and use the map operator to transform the response into the validator return type, and also make it expect an abstract control as argument, like so:

 checkDeliveriesDateValidator(ctrl: AbstractControl) {
    // add in basic null checks
    return (ctrl && ctrl.value) ? this.SS.getOrdersPerDate({ date: ctrl.value }).pipe(
      map(res => {
        console.log(res);
        if (res.length>3){
          //formcontrol for e should turn invalid 
          return {exists: true};
        }
        else{
          return null;
        }
      })
    ) : null;
  }

then use like:

DateOfDelivery: new FormControl('', Validators.required, checkDeliveriesDateValidator)

推荐阅读