【发布时间】: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);
};
}
...后端调用是否返回false 或true。
仅供参考,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。