【问题标题】:Angular custom validation using http service - Cannot read property of undefined使用 http 服务的角度自定义验证 - 无法读取未定义的属性
【发布时间】:2017-10-24 08:16:04
【问题描述】:

我在运行代码时收到此错误:无法读取未定义的属性“getClientEmails”。 如果我从 ngOnInit 调用“clientService”,它会起作用,但不能从“shouldBeUnique”方法内部调用

export class ClientFormComponent {

  emails: any = {};

  form = new FormGroup({
    email: new FormControl('',
      null,
      this.shouldBeUnique),

    password: new FormControl('', Validators.required),
    confirm: new FormControl('', Validators.required),
    firstname: new FormControl('', Validators.required),
    lastname: new FormControl('', Validators.required),
    address: new FormControl('', Validators.required),
    phone: new FormControl('', Validators.required),
    medical: new FormControl('', Validators.required)
  });

  constructor(public clientService: ClientService) { }


  shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {

    this.clientService.getClientEmails().subscribe(email => {
      this.emails = email;
      console.log(this.emails);
    });

    return new Promise((resolve, reject) => {

      if (control.value === '')
        resolve({ shouldBeUnique: true });
      else
        resolve(null);
    });
  }
}

【问题讨论】:

  • 进行服务调用并返回承诺有什么意义,因为您的验证器只检查控制值是否为空?
  • 当我有服务调用工作时,我将用真实检查替换空字符串

标签: angular


【解决方案1】:

替换

this.shouldBeUnique

通过

(control: AbstractControl) => this.shouldBeUnique(control)

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2019-04-28
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多