当我实际进行异步调用时,我的异步验证器不工作(但当我用 . 模拟它时工作Observable.of(result)
。html
看起来像这样:
<div class="form-group">
<label for="emailAddress" class="control-label">Email</label>
<input type="email"
id="emailAddress"
class="form-control"
[(ngModel)]="parent.EmailAddress"
name="emailAddress"
[ngModelOptions]="{updateOn: 'blur'}"
appDuplicateEmailValidator
#emailAddress = "ngModel">
</div>
有问题的验证器是appDuplicateEmailValidator
.
验证代码如下所示:
public validate(control: AbstractControl): Observable<ValidationErrors | null> {
// return observableOf({ 'isDuplicateEmail': true });
return this.checkForDupeUserAndGetValidationState(emailAddress);
}
private checkForDupeUserAndGetValidationState(emailAddress): Observable<ValidationErrors | null> {
const validationStateObs: Observable<ValidationErrors | null> = new Observable(observer => {
this.adminService.getUser(emailAddress).subscribe(
(res: any) => {
const validationState = !!res ? observableOf({ 'isDuplicateEmail': true }) : null;
console.log('Observer next, validation state: ', validationState); // Gets correct val state
observer.next(validationState);
console.log('Is it hitting this'); // Gets hit
}, (err) => {
observer.next(null);
});
});
一个重要的注意事项是,当我取消注释时// return observableOf({ 'isDuplicateEmail': true });
,一切都按预期工作。但是您看到上面的代码的方式,它不起作用,即使 observable 返回正确的值(将其记录为使用过的调试器)。“它不起作用”是指表单控件永远不会进入错误状态,如下所示:
<pre>IS INVALID: {{emailAddress.invalid}}</pre>
<pre>ERRORS: {{emailAddress.errors | json}}</pre>
为什么以及如何解决它?