【问题标题】:Issue with angular 2 async validators array: async validator always returns validation error角度 2 异步验证器数组的问题:异步验证器始终返回验证错误
【发布时间】:2017-01-24 02:26:43
【问题描述】:

我在使用 angular 2 异步验证器时遇到问题。

我有以下组件:

@Component({
  templateUrl: './send-activation-information.component.html'
})
export class SendActivationInformationComponent implements OnInit {

  activationInformationForm: FormGroup;
  submitted: boolean = false;  

  constructor(private userAccountService: UserAccountService,
              private formBuilder: FormBuilder,
              private router: Router) {
  }

  ngOnInit() {
    this.activationInformationForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.pattern(AppConstants.EMAIL_PATTERN)
      ], [
        validateEmailKnownFactory(this.userAccountService),
        validateUserAccountNonActivatedFactory(this.userAccountService)
      ]]
    });
  }

  sendActivationInformation() {
    this.submitted = true;
    if (this.activationInformationForm.valid) {     
        this.userAccountService.sendActivationInformation(this.activationInformationForm.value)
        .subscribe(() => this.router.navigate(['/sendactivationinformation/success']));
    }
  }
}

它使用两个数组中指定的两个同步验证器和两个异步验证器。

由于某种原因,以下异步验证器总是指示验证错误

export function validateUserAccountNonActivatedFactory(userAccountService: UserAccountService): {[key: string]: any} {
  return (control: AbstractControl) => {
    return userAccountService.userAccountAlreadyActivated(control.value)
      .map(alreadyActivated => alreadyActivated ? {userAccountNonActivatedValidator: {alreadyActivated: true}} : null);
  };
}

...后端调用是否返回falsetrue

仅供参考,userAccountAlreadyActivated 对后端进行 http 调用,如下所示:

  userAccountAlreadyActivated(email: string) {
    let body = 'email=' + email;
    return this.http.get(this.urls.USER_ACCOUNT.ALREADY_ACTIVATED + body);
  }

【问题讨论】:

  • 我怀疑这个问题与我指定异步验证器数组的方式有关,但我不确定。
  • 如果你只添加异步验证器甚至只添加一个异步验证器,它是否有效?
  • 没有。你是对的,验证器不能单独工作(我已经评论了第一个验证器)。并且无论是从后端返回true还是false都是错误的......
  • 您是否尝试过像var f = validateUserAccountNonActivatedFactory(this.userAccountService); f(someControl).subscribe(val => console.log(val)); 那样直接调用验证器来进行调试?
  • 你能保证这是一个异步相关的事情吗?我对非异步数组也有同样的问题:stackoverflow.com/questions/41769431/… 另外,您使用的是什么角度版本?我在 2.4.4。

标签: angular angular2-forms


【解决方案1】:

忘记将结果映射到 json...

因此,从:

  userAccountAlreadyActivated(email: string) {
    let body = 'email=' + email;
    return this.http.get(this.urls.USER_ACCOUNT.ALREADY_ACTIVATED + body);
  }

到:

  userAccountAlreadyActivated(email: string) {
    let body = 'email=' + email;
    return this.http.get(this.urls.USER_ACCOUNT.ALREADY_ACTIVATED + body).map(res => res.json());
  }

修复了这个问题 - 与角度验证器无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2021-07-12
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多