2

我正在尝试使用装饰器将验证器方法传递到 angular4 反应形式以进行验证。

零件

@AutoUnsubscribe( [] )
@Component(
    {
      selector: 'pim-mat-input',
      template: `
        <form
            autocomplete = 'off'
            [formGroup] = 'form'>

          <section
              fxLayout = 'column'
              fxLayoutAlign = 'start start'>
            <mat-form-field>
              <input
                  #input
                  matInput
                  formControlName = 'entry'>
            </mat-form-field>
          </section>

        </form>
      `,
      styles: []
    } )
export class PimMatInputComponent implements AfterViewInit, OnDestroy, OnInit {  
  protected entryCtrl: AbstractControl
  protected form: FormGroup

  constructor( private _fb: FormBuilder ) {
  }

  @validators( [ PimNgxFormValidators.notEmpty ] )
  ngOnInit() {
    this.form = this._fb.group(
        { entry: [ '', [ /*PimNgxFormValidators.notEmpty goes here*/] ] } )

    this.entryCtrl = this.form.controls[ 'entry' ]

  }

  ngOnDestroy() {
    // needed for @AutoUnsubscribe()
  }

  ngAfterViewInit(): void {
  }
}

装饰器尝试 - 不完整

export function validators( vals: Array<Function> = [] ) {
  let form: FormGroup
  return function( target: any, member: string, descriptor: PropertyDescriptor ) {

    const originalMethod = descriptor.value

    descriptor.value = function( ...args ) {

     // What should I put here to allow the argument to be used in the component
    }
    return descriptor
  }
}

如何让装饰器将其参数传递给表单中的入口控件?

干杯

4

1 回答 1

0

尝试类似的东西

export function validators(...vals: Array<(...args: any[]) => void>) {
  let form: FormGroup
  return function <T extends object>(target: T, key: keyof T, descriptor: PropertyDescriptor) {

    const originalMethod = descriptor.value

    descriptor.value = function(...args: any[]) {
       performValidation(...args);
       originalMethod.call(target, ...args);
    }
    return descriptor;
  }
}

泛型的原因只是为了确保方法是由目标对象定义的。这不是必需的,但我觉得它很有价值。

在调用方法时将验证数组 , 传递vals给框架更为复杂。

最简单的方法是将验证器本身存储在类的一个字段中,以便它们可用,但这有点违背了使用装饰器的目的。

例如我们可以写

export function validators(...vals: Array<(...args: any[]) => void>) {
  return function <T extends {validators: Array<(...args: any[]) => void>}>(target: T) {
    target.validators = vals;
  }
}

这样我们的班级看起来像

export class PimMatInputComponent {
  validators: (...vals: Array<(...args: any[]) => void> = [];

  @validators([PimNgxFormValidators.notEmpty])
  ngOnInit() {
    this.form = this._fb.group({
      entry: [ '', [this.validators]]
    });

    this.entryCtrl = this.form.controls['entry'];
  }
}

如您所见,在这种情况下我们没有触及描述符,因为我们只是使用装饰器将验证器附加到类。但这使得装饰器的使用变得多余,因为我们可以更易读地编写

export class PimMatInputComponent {
  validators = [PimNgxFormValidators.notEmpty];

  ngOnInit() {
    this.form = this._fb.group({
      entry: [ '', [this.validators]]
    });

    this.entryCtrl = this.form.controls['entry'];
  }
}

方法装饰器对于验证包装方法体很有用。通常它们可用于验证方法的参数,但它们不能将代码注入实现本身。

例如,如果我们希望验证传递给方法的参数,我们可以编写如下装饰器

export function validateArguments(...validators: Array<(...as: any[]) => void>) {
  return <T extends object>(target, key: keyof T, descriptor: PropertyDescriptor) => {
    const originalMethod = descriptor.value;
    descriptor.value = (...args: any[]) => {
      args.forEach(argument => {
        validators.forEach(validate => {
          validate(argument);
        });
      });

      originalMethod.call(target, ...args);
    };
  };
}

然后我们可以将它应用到任意方法并传入验证器,如下所示

export class A {
  @validateArguments(arg => {
    if (arg === undefined) {
      throw Error('required parameter not specified');
    }
  })
  m(a, b, c) {
    console.log('If we got here no arguments were undefined.');
  }
}
于 2017-10-11T04:17:03.370 回答