angular 2异步验证器数组的问题:异步验证器始终返回验证错误

时间:2017-01-20 15:17:54

标签: angular angular2-forms

我对使用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);
  }

1 个答案:

答案 0 :(得分:0)

忘记将结果映射到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());
  }

解决了这个问题 - 这与角度验证器无关。