我创建了一个AsyncValidator
来检查userName的唯一性。
根据this示例,我添加了500毫秒的延迟。
但是,如果输入值没有通过特定要求,我根本不知道如何防止服务(http)被调用。
import { Injectable } from "@angular/core";
import { AsyncValidator, AbstractControl } from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { UsersService } from "../services/UsersService";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
@Injectable()
export class UniqueUserNameAsyncValidator implements AsyncValidator {
constructor(private usersService: UsersService) {
}
validate(c: AbstractControl): Promise<any> | Observable<any> {
return Observable.timer(500).switchMap(() => {
if(!c.value || c.value.length < 4) {
// TODO
// prevent call to service if the control value is null / empty
// return null; // Doesn't work
}
return this.usersService.getByName(c.value)
.map(p => {
return { uniqueUserName: true };
});
});
}
}
答案 0 :(得分:0)
为什么不翻转要求? 改变代码如
validate(c: AbstractControl): Promise<any> | Observable<any> {
return Observable.timer(500).switchMap(() => {
if(c.value || c.value.length >= 4) {
return this.usersService.getByName(c.value)
.map(p => {
return { uniqueUserName: true };
});
}else{
//do things you want if requirements are not fulfilled
}
});
}