我在使用 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);
};
}
。后端调用是否返回false
或true
。
仅供参考,userAccountAlreadyActivated
对后端进行 http 调用,如下所示:
userAccountAlreadyActivated(email: string) {
let body = 'email=' + email;
return this.http.get(this.urls.USER_ACCOUNT.ALREADY_ACTIVATED + body);
}
我忘了将结果映射到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());
}
修复了这个问题 - 这与 Angular 验证器无关。