【发布时间】:2018-07-11 19:28:19
【问题描述】:
我创建了一个AsyncValidator 来检查用户名的唯一性。
基于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 };
});
});
}
}
【问题讨论】:
标签: angular typescript angular2-forms angular2-observables angular-validation