【问题标题】:Angular async reactive form Validation角度异步反应形式验证
【发布时间】:2018-10-20 14:27:22
【问题描述】:

我一直在寻找可以将异步验证器实现为 Angular 反应形式的大量教程,但我总是遇到错误。

我需要做的是检查字段中写入的值是否存在于存储在服务中的对象数组中。

问题是,当我与固定值进行比较时,验证器工作正常,但是当我尝试使用服务时,它说服务未定义。

表单代码:

ngOnInit() {
 this.FormNuevaConf =this.fb.group({
  'codigo': [null,null],
  'valor': [null,null,this.valorUnicoValidator]
})}

验证器代码:

valorUnicoValidator (control: AbstractControl, service:UnidadesService): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return of(service.subscribe(control) === control.value).pipe(
  map(result => result ? { invalid: true } : null)
  );}

subscribe(control) 是服务中的一个函数,如果在从 db 查询返回的对象数组中找到 control.value,则返回一个值。

我还没有找到关于如何构建异步验证器的清晰解释,如果你有可以推荐我的,我会感谢的。

【问题讨论】:

标签: angular validation asynchronous angular-reactive-forms


【解决方案1】:

服务不能注入验证器,您必须在组件类的构造函数中将其作为私有注入,然后在验证器中使用它,因为您可以访问它。 p>

类似:

constructor(private service: UnidadesService) {}

ngOnInit() {
  this.FormNuevaConf =this.fb.group({
    'codigo': [null,null],
    'valor': [null,null,this.valorUnicoValidator]
  })
}

valorUnicoValidator (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return of(this.service.subscribe(control) === control.value).pipe(
      map(result => result ? { invalid: true } : null)
);}

【讨论】:

    【解决方案2】:

    如果您的组件具有您想要的服务实例的副本,您可以像这样创建验证器构建器。

    myValidator.validator.ts:

    export function MyValidator(service: MyService) {
        return (control: AbstractControl): { [key: string]: any } | null => {
            if (service.getValue()) {
                return { Error: true };
            } else {
                return null;
            }
        };
    }
    

    在您的组件中:

    this.noteForm.addControl("MyFormContorl", new FormControl(null,
                [Validators.required, MyValidator(this.myService)])); 
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2020-04-26
    • 1970-01-01
    相关资源
    最近更新 更多