如何在 angular 2 中为异步验证器添加去抖动时间?
How to add debounce time to an async validator in angular 2?
这是我的异步验证器,它没有去抖动时间,我该如何添加它?
static emailExist(_signupService:SignupService) {
return (control:Control) => {
return new Promise((resolve, reject) => {
_signupService.checkEmail(control.value)
.subscribe(
data => {
if (data.response.available == true) {
resolve(null);
} else {
resolve({emailExist: true});
}
},
err => {
resolve({emailExist: true});
})
})
}
}
不可能开箱即用,因为验证器是在 input
事件用于触发更新时直接触发的。查看源代码中的这一行:
如果您想在此级别利用去抖动时间,您需要获得与相应 DOM 元素的 input
事件直接链接的可观察对象。 Github 中的这个问题可以为您提供上下文:
在您的情况下,解决方法是利用 observable 的 fromEvent
方法实现自定义值访问器。
这是一个示例:
const DEBOUNCE_INPUT_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => DebounceInputControlValueAccessor), multi: true});
@Directive({
selector: '[debounceTime]',
//host: {'(change)': 'doOnChange($event.target)', '(blur)': 'onTouched()'},
providers: [DEBOUNCE_INPUT_VALUE_ACCESSOR]
})
export class DebounceInputControlValueAccessor implements ControlValueAccessor {
onChange = (_) => {};
onTouched = () => {};
@Input()
debounceTime:number;
constructor(private _elementRef: ElementRef, private _renderer:Renderer) {
}
ngAfterViewInit() {
Observable.fromEvent(this._elementRef.nativeElement, 'keyup')
.debounceTime(this.debounceTime)
.subscribe((event) => {
this.onChange(event.target.value);
});
}
writeValue(value: any): void {
var normalizedValue = isBlank(value) ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn: () => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
}
并这样使用:
function validator(ctrl) {
console.log('validator called');
console.log(ctrl);
}
@Component({
selector: 'app'
template: `
<form>
<div>
<input [debounceTime]="2000" [ngFormControl]="ctrl"/>
</div>
value : {{ctrl.value}}
</form>
`,
directives: [ DebounceInputControlValueAccessor ]
})
export class App {
constructor(private fb:FormBuilder) {
this.ctrl = new Control('', validator);
}
}
看到这个 plunkr:https://plnkr.co/edit/u23ZgaXjAvzFpeScZbpJ?p=preview。
实现这个其实很简单(这不是针对你的情况,而是一般的例子)
private emailTimeout;
emailAvailability(control: Control) {
clearTimeout(this.emailTimeout);
return new Promise((resolve, reject) => {
this.emailTimeout = setTimeout(() => {
this._service.checkEmail({email: control.value})
.subscribe(
response => resolve(null),
error => resolve({availability: true}));
}, 600);
});
}
Angular 4+, 使用 Observable.timer(debounceTime)
:
@izupet 的回答是正确的,但值得注意的是,当你使用 Observable 时,它会更简单:
emailAvailability(control: Control) {
return Observable.timer(500).switchMap(()=>{
return this._service.checkEmail({email: control.value})
.mapTo(null)
.catch(err=>Observable.of({availability: true}));
});
}
自从 angular 4 已发布,如果发送新值进行检查,Angular 会在 Observable
仍在计时器中暂停时取消订阅,因此您不必实际上需要自己管理setTimeout
/clearTimeout
逻辑。
使用 timer
和 Angular 的异步验证器行为,我们重新创建了 RxJS debounceTime
.
RxJs 的替代解决方案如下。
/**
* From a given remove validation fn, it returns the AsyncValidatorFn
* @param remoteValidation: The remote validation fn that returns an observable of <ValidationErrors | null>
* @param debounceMs: The debounce time
*/
debouncedAsyncValidator<TValue>(
remoteValidation: (v: TValue) => Observable<ValidationErrors | null>,
remoteError: ValidationErrors = { remote: "Unhandled error occurred." },
debounceMs = 300
): AsyncValidatorFn {
const values = new BehaviorSubject<TValue>(null);
const validity$ = values.pipe(
debounceTime(debounceMs),
switchMap(remoteValidation),
catchError(() => of(remoteError)),
take(1)
);
return (control: AbstractControl) => {
if (!control.value) return of(null);
values.next(control.value);
return validity$;
};
}
用法:
const validator = debouncedAsyncValidator<string>(v => {
return this.myService.validateMyString(v).pipe(
map(r => {
return r.isValid ? { foo: "String not valid" } : null;
})
);
});
const control = new FormControl('', null, validator);
我遇到了同样的问题。我想要一个消除输入抖动的解决方案,并且只在输入更改时请求后端。
验证器中带有计时器的所有变通方法都有问题,即它们会在每次击键时请求后端。他们只去抖动验证响应。这不是我们打算做的。您希望对输入进行去抖动和区分,然后才请求后端。
我的解决方案如下(使用反应形式和材料 2):
组件
@Component({
selector: 'prefix-username',
templateUrl: './username.component.html',
styleUrls: ['./username.component.css']
})
export class UsernameComponent implements OnInit, OnDestroy {
usernameControl: FormControl;
destroyed$ = new Subject<void>(); // observes if component is destroyed
validated$: Subject<boolean>; // observes if validation responses
changed$: Subject<string>; // observes changes on username
constructor(
private fb: FormBuilder,
private service: UsernameService,
) {
this.createForm();
}
ngOnInit() {
this.changed$ = new Subject<string>();
this.changed$
// only take until component destroyed
.takeUntil(this.destroyed$)
// at this point the input gets debounced
.debounceTime(300)
// only request the backend if changed
.distinctUntilChanged()
.subscribe(username => {
this.service.isUsernameReserved(username)
.subscribe(reserved => this.validated$.next(reserved));
});
this.validated$ = new Subject<boolean>();
this.validated$.takeUntil(this.destroyed$); // only take until component not destroyed
}
ngOnDestroy(): void {
this.destroyed$.next(); // complete all listening observers
}
createForm(): void {
this.usernameControl = this.fb.control(
'',
[
Validators.required,
],
[
this.usernameValodator()
]);
}
usernameValodator(): AsyncValidatorFn {
return (c: AbstractControl) => {
const obs = this.validated$
// get a new observable
.asObservable()
// only take until component destroyed
.takeUntil(this.destroyed$)
// only take one item
.take(1)
// map the error
.map(reserved => reserved ? {reserved: true} : null);
// fire the changed value of control
this.changed$.next(c.value);
return obs;
}
}
}
模板
<mat-form-field>
<input
type="text"
placeholder="Username"
matInput
formControlName="username"
required/>
<mat-hint align="end">Your username</mat-hint>
</mat-form-field>
<ng-template ngProjectAs="mat-error" bind-ngIf="usernameControl.invalid && (usernameControl.dirty || usernameControl.touched) && usernameControl.errors.reserved">
<mat-error>Sorry, you can't use this username</mat-error>
</ng-template>
RxJS 6 示例:
import { of, timer } from 'rxjs';
import { catchError, mapTo, switchMap } from 'rxjs/operators';
validateSomething(control: AbstractControl) {
return timer(SOME_DEBOUNCE_TIME).pipe(
switchMap(() => this.someService.check(control.value).pipe(
// Successful response, set validator to null
mapTo(null),
// Set error object on error response
catchError(() => of({ somethingWring: true }))
)
)
);
}
这是我使用 rxjs6
的实时 Angular 项目的示例
import { ClientApiService } from '../api/api.service';
import { AbstractControl } from '@angular/forms';
import { HttpParams } from '@angular/common/http';
import { map, switchMap } from 'rxjs/operators';
import { of, timer } from 'rxjs/index';
export class ValidateAPI {
static createValidator(service: ClientApiService, endpoint: string, paramName) {
return (control: AbstractControl) => {
if (control.pristine) {
return of(null);
}
const params = new HttpParams({fromString: `${paramName}=${control.value}`});
return timer(1000).pipe(
switchMap( () => service.get(endpoint, {params}).pipe(
map(isExists => isExists ? {valueExists: true} : null)
)
)
);
};
}
}
下面是我如何以我的反应形式使用它
this.form = this.formBuilder.group({
page_url: this.formBuilder.control('', [Validators.required], [ValidateAPI.createValidator(this.apiService, 'meta/check/pageurl', 'pageurl')])
});
对于仍然对此主题感兴趣的任何人,请务必在 angular 6 document 中注意这一点:
- They must return a Promise or an Observable,
- The observable returned must be finite, meaning it must complete at some point. To convert an infinite observable into a finite one, pipe the observable through a filtering operator such as first, last, take, or takeUntil.
注意上面的第二个要求。
这是一个 AsyncValidatorFn
实现:
const passwordReapeatValidator: AsyncValidatorFn = (control: FormGroup) => {
return of(1).pipe(
delay(1000),
map(() => {
const password = control.get('password');
const passwordRepeat = control.get('passwordRepeat');
return password &&
passwordRepeat &&
password.value === passwordRepeat.value
? null
: { passwordRepeat: true };
})
);
};
这是一个服务,returns 一个使用 debounceTime(...)
和 distinctUntilChanged()
的验证器函数:
@Injectable({
providedIn: 'root'
})
export class EmailAddressAvailabilityValidatorService {
constructor(private signupService: SignupService) {}
debouncedSubject = new Subject<string>();
validatorSubject = new Subject();
createValidator() {
this.debouncedSubject
.pipe(debounceTime(500), distinctUntilChanged())
.subscribe(model => {
this.signupService.checkEmailAddress(model).then(res => {
if (res.value) {
this.validatorSubject.next(null)
} else {
this.validatorSubject.next({emailTaken: true})
}
});
});
return (control: AbstractControl) => {
this.debouncedSubject.next(control.value);
let prom = new Promise<any>((resolve, reject) => {
this.validatorSubject.subscribe(
(result) => resolve(result)
);
});
return prom
};
}
}
用法:
emailAddress = new FormControl('',
[Validators.required, Validators.email],
this.validator.createValidator() // async
);
如果您添加验证器 Validators.required
和 Validators.email
,则仅当输入字符串为非空且有效的电子邮件地址时才会发出请求。这样做是为了避免不必要的 API 调用。
保持简单:没有超时,没有延迟,没有自定义 Observable
// assign the async validator to a field
this.cardAccountNumber.setAsyncValidators(this.uniqueCardAccountValidatorFn());
// or like this
new FormControl('', [], [ this.uniqueCardAccountValidator() ]);
// subscribe to control.valueChanges and define pipe
uniqueCardAccountValidatorFn(): AsyncValidatorFn {
return control => control.valueChanges
.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap(value => this.customerService.isCardAccountUnique(value)),
map((unique: boolean) => (unique ? null : {'cardAccountNumberUniquenessViolated': true})),
first()); // important to make observable finite
}
事情可以简化一点
export class SomeAsyncValidator {
static createValidator = (someService: SomeService) => (control: AbstractControl) =>
timer(500)
.pipe(
map(() => control.value),
switchMap((name) => someService.exists({ name })),
map(() => ({ nameTaken: true })),
catchError(() => of(null)));
}
Angular 9+ asyncValidator w/ debounce
@n00dl3 有正确答案。我喜欢依靠 Angular 代码来取消订阅并通过抛出一个定时暂停来创建一个新的异步验证器。 Angular 和 RxJS API 自该答案撰写以来已经发展,因此我发布了一些更新的代码。
另外,我做了一些修改。 (1) 代码应报告已捕获的错误,而不是将其隐藏在电子邮件地址的匹配项下,否则我们会使用户感到困惑。如果网络故障,为什么说电子邮件匹配?! UI 表示代码将区分电子邮件冲突和网络错误。 (2) 验证器应该在时间延迟之前捕获控件的值,以防止任何可能的竞争条件。 (3) 使用 delay
而不是 timer
因为后者将每半秒触发一次,如果我们的网络速度较慢并且电子邮件检查需要很长时间(一秒),计时器将继续重新触发 switchMap 和通话永远不会完成。
Angular 9+ 兼容片段:
emailAvailableValidator(control: AbstractControl) {
return of(control.value).pipe(
delay(500),
switchMap((email) => this._service.checkEmail(email).pipe(
map(isAvail => isAvail ? null : { unavailable: true }),
catchError(err => { error: err }))));
}
PS:任何想要深入研究 Angular 来源的人(我强烈推荐),您可以找到运行异步验证的 Angular 代码 here and the code that cancels subscriptions here which calls into this .所有相同的文件都在 updateValueAndValidity
.
下
尝试使用计时器。
static verificarUsuario(usuarioService: UsuarioService) {
return (control: AbstractControl) => {
return timer(1000).pipe(
switchMap(()=>
usuarioService.buscar(control.value).pipe(
map( (res: Usuario) => {
console.log(res);
return Object.keys(res).length === 0? null : { mensaje: `El usuario ${control.value} ya existe` };
})
)
)
)
}
}
由于我们正试图减少我们向服务器发出的请求数量,我还建议添加一个检查以确保只将有效的电子邮件发送到服务器进行检查
我使用了 JavaScript: HTML Form - email validation
中的简单 RegEx
我们还使用 timer(1000)
创建一个在 1 秒后执行的 Observable。
设置了这两项后,我们只检查电子邮件地址是否有效,并且仅在用户输入后 1 秒后检查。 switchMap
如果有新的请求,运营商将取消之前的请求
const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
const emailExists = control =>
timer(1000).pipe(
switchMap(() => {
if (emailRegExp.test(control.value)) {
return MyService.checkEmailExists(control.value);
}
return of(false);
}),
map(exists => (exists ? { emailExists: true } : null))
);
然后我们可以将此验证器与 Validator.pattern()
函数一起使用
myForm = this.fb.group({
email: [ "", { validators: [Validators.pattern(emailRegExp)], asyncValidators: [emailExists] }]
});
这是我的异步验证器,它没有去抖动时间,我该如何添加它?
static emailExist(_signupService:SignupService) {
return (control:Control) => {
return new Promise((resolve, reject) => {
_signupService.checkEmail(control.value)
.subscribe(
data => {
if (data.response.available == true) {
resolve(null);
} else {
resolve({emailExist: true});
}
},
err => {
resolve({emailExist: true});
})
})
}
}
不可能开箱即用,因为验证器是在 input
事件用于触发更新时直接触发的。查看源代码中的这一行:
如果您想在此级别利用去抖动时间,您需要获得与相应 DOM 元素的 input
事件直接链接的可观察对象。 Github 中的这个问题可以为您提供上下文:
在您的情况下,解决方法是利用 observable 的 fromEvent
方法实现自定义值访问器。
这是一个示例:
const DEBOUNCE_INPUT_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => DebounceInputControlValueAccessor), multi: true});
@Directive({
selector: '[debounceTime]',
//host: {'(change)': 'doOnChange($event.target)', '(blur)': 'onTouched()'},
providers: [DEBOUNCE_INPUT_VALUE_ACCESSOR]
})
export class DebounceInputControlValueAccessor implements ControlValueAccessor {
onChange = (_) => {};
onTouched = () => {};
@Input()
debounceTime:number;
constructor(private _elementRef: ElementRef, private _renderer:Renderer) {
}
ngAfterViewInit() {
Observable.fromEvent(this._elementRef.nativeElement, 'keyup')
.debounceTime(this.debounceTime)
.subscribe((event) => {
this.onChange(event.target.value);
});
}
writeValue(value: any): void {
var normalizedValue = isBlank(value) ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn: () => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
}
并这样使用:
function validator(ctrl) {
console.log('validator called');
console.log(ctrl);
}
@Component({
selector: 'app'
template: `
<form>
<div>
<input [debounceTime]="2000" [ngFormControl]="ctrl"/>
</div>
value : {{ctrl.value}}
</form>
`,
directives: [ DebounceInputControlValueAccessor ]
})
export class App {
constructor(private fb:FormBuilder) {
this.ctrl = new Control('', validator);
}
}
看到这个 plunkr:https://plnkr.co/edit/u23ZgaXjAvzFpeScZbpJ?p=preview。
实现这个其实很简单(这不是针对你的情况,而是一般的例子)
private emailTimeout;
emailAvailability(control: Control) {
clearTimeout(this.emailTimeout);
return new Promise((resolve, reject) => {
this.emailTimeout = setTimeout(() => {
this._service.checkEmail({email: control.value})
.subscribe(
response => resolve(null),
error => resolve({availability: true}));
}, 600);
});
}
Angular 4+, 使用 Observable.timer(debounceTime)
:
@izupet 的回答是正确的,但值得注意的是,当你使用 Observable 时,它会更简单:
emailAvailability(control: Control) {
return Observable.timer(500).switchMap(()=>{
return this._service.checkEmail({email: control.value})
.mapTo(null)
.catch(err=>Observable.of({availability: true}));
});
}
自从 angular 4 已发布,如果发送新值进行检查,Angular 会在 Observable
仍在计时器中暂停时取消订阅,因此您不必实际上需要自己管理setTimeout
/clearTimeout
逻辑。
使用 timer
和 Angular 的异步验证器行为,我们重新创建了 RxJS debounceTime
.
RxJs 的替代解决方案如下。
/**
* From a given remove validation fn, it returns the AsyncValidatorFn
* @param remoteValidation: The remote validation fn that returns an observable of <ValidationErrors | null>
* @param debounceMs: The debounce time
*/
debouncedAsyncValidator<TValue>(
remoteValidation: (v: TValue) => Observable<ValidationErrors | null>,
remoteError: ValidationErrors = { remote: "Unhandled error occurred." },
debounceMs = 300
): AsyncValidatorFn {
const values = new BehaviorSubject<TValue>(null);
const validity$ = values.pipe(
debounceTime(debounceMs),
switchMap(remoteValidation),
catchError(() => of(remoteError)),
take(1)
);
return (control: AbstractControl) => {
if (!control.value) return of(null);
values.next(control.value);
return validity$;
};
}
用法:
const validator = debouncedAsyncValidator<string>(v => {
return this.myService.validateMyString(v).pipe(
map(r => {
return r.isValid ? { foo: "String not valid" } : null;
})
);
});
const control = new FormControl('', null, validator);
我遇到了同样的问题。我想要一个消除输入抖动的解决方案,并且只在输入更改时请求后端。
验证器中带有计时器的所有变通方法都有问题,即它们会在每次击键时请求后端。他们只去抖动验证响应。这不是我们打算做的。您希望对输入进行去抖动和区分,然后才请求后端。
我的解决方案如下(使用反应形式和材料 2):
组件
@Component({
selector: 'prefix-username',
templateUrl: './username.component.html',
styleUrls: ['./username.component.css']
})
export class UsernameComponent implements OnInit, OnDestroy {
usernameControl: FormControl;
destroyed$ = new Subject<void>(); // observes if component is destroyed
validated$: Subject<boolean>; // observes if validation responses
changed$: Subject<string>; // observes changes on username
constructor(
private fb: FormBuilder,
private service: UsernameService,
) {
this.createForm();
}
ngOnInit() {
this.changed$ = new Subject<string>();
this.changed$
// only take until component destroyed
.takeUntil(this.destroyed$)
// at this point the input gets debounced
.debounceTime(300)
// only request the backend if changed
.distinctUntilChanged()
.subscribe(username => {
this.service.isUsernameReserved(username)
.subscribe(reserved => this.validated$.next(reserved));
});
this.validated$ = new Subject<boolean>();
this.validated$.takeUntil(this.destroyed$); // only take until component not destroyed
}
ngOnDestroy(): void {
this.destroyed$.next(); // complete all listening observers
}
createForm(): void {
this.usernameControl = this.fb.control(
'',
[
Validators.required,
],
[
this.usernameValodator()
]);
}
usernameValodator(): AsyncValidatorFn {
return (c: AbstractControl) => {
const obs = this.validated$
// get a new observable
.asObservable()
// only take until component destroyed
.takeUntil(this.destroyed$)
// only take one item
.take(1)
// map the error
.map(reserved => reserved ? {reserved: true} : null);
// fire the changed value of control
this.changed$.next(c.value);
return obs;
}
}
}
模板
<mat-form-field>
<input
type="text"
placeholder="Username"
matInput
formControlName="username"
required/>
<mat-hint align="end">Your username</mat-hint>
</mat-form-field>
<ng-template ngProjectAs="mat-error" bind-ngIf="usernameControl.invalid && (usernameControl.dirty || usernameControl.touched) && usernameControl.errors.reserved">
<mat-error>Sorry, you can't use this username</mat-error>
</ng-template>
RxJS 6 示例:
import { of, timer } from 'rxjs';
import { catchError, mapTo, switchMap } from 'rxjs/operators';
validateSomething(control: AbstractControl) {
return timer(SOME_DEBOUNCE_TIME).pipe(
switchMap(() => this.someService.check(control.value).pipe(
// Successful response, set validator to null
mapTo(null),
// Set error object on error response
catchError(() => of({ somethingWring: true }))
)
)
);
}
这是我使用 rxjs6
的实时 Angular 项目的示例import { ClientApiService } from '../api/api.service';
import { AbstractControl } from '@angular/forms';
import { HttpParams } from '@angular/common/http';
import { map, switchMap } from 'rxjs/operators';
import { of, timer } from 'rxjs/index';
export class ValidateAPI {
static createValidator(service: ClientApiService, endpoint: string, paramName) {
return (control: AbstractControl) => {
if (control.pristine) {
return of(null);
}
const params = new HttpParams({fromString: `${paramName}=${control.value}`});
return timer(1000).pipe(
switchMap( () => service.get(endpoint, {params}).pipe(
map(isExists => isExists ? {valueExists: true} : null)
)
)
);
};
}
}
下面是我如何以我的反应形式使用它
this.form = this.formBuilder.group({
page_url: this.formBuilder.control('', [Validators.required], [ValidateAPI.createValidator(this.apiService, 'meta/check/pageurl', 'pageurl')])
});
对于仍然对此主题感兴趣的任何人,请务必在 angular 6 document 中注意这一点:
- They must return a Promise or an Observable,
- The observable returned must be finite, meaning it must complete at some point. To convert an infinite observable into a finite one, pipe the observable through a filtering operator such as first, last, take, or takeUntil.
注意上面的第二个要求。
这是一个 AsyncValidatorFn
实现:
const passwordReapeatValidator: AsyncValidatorFn = (control: FormGroup) => {
return of(1).pipe(
delay(1000),
map(() => {
const password = control.get('password');
const passwordRepeat = control.get('passwordRepeat');
return password &&
passwordRepeat &&
password.value === passwordRepeat.value
? null
: { passwordRepeat: true };
})
);
};
这是一个服务,returns 一个使用 debounceTime(...)
和 distinctUntilChanged()
的验证器函数:
@Injectable({
providedIn: 'root'
})
export class EmailAddressAvailabilityValidatorService {
constructor(private signupService: SignupService) {}
debouncedSubject = new Subject<string>();
validatorSubject = new Subject();
createValidator() {
this.debouncedSubject
.pipe(debounceTime(500), distinctUntilChanged())
.subscribe(model => {
this.signupService.checkEmailAddress(model).then(res => {
if (res.value) {
this.validatorSubject.next(null)
} else {
this.validatorSubject.next({emailTaken: true})
}
});
});
return (control: AbstractControl) => {
this.debouncedSubject.next(control.value);
let prom = new Promise<any>((resolve, reject) => {
this.validatorSubject.subscribe(
(result) => resolve(result)
);
});
return prom
};
}
}
用法:
emailAddress = new FormControl('',
[Validators.required, Validators.email],
this.validator.createValidator() // async
);
如果您添加验证器 Validators.required
和 Validators.email
,则仅当输入字符串为非空且有效的电子邮件地址时才会发出请求。这样做是为了避免不必要的 API 调用。
保持简单:没有超时,没有延迟,没有自定义 Observable
// assign the async validator to a field
this.cardAccountNumber.setAsyncValidators(this.uniqueCardAccountValidatorFn());
// or like this
new FormControl('', [], [ this.uniqueCardAccountValidator() ]);
// subscribe to control.valueChanges and define pipe
uniqueCardAccountValidatorFn(): AsyncValidatorFn {
return control => control.valueChanges
.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap(value => this.customerService.isCardAccountUnique(value)),
map((unique: boolean) => (unique ? null : {'cardAccountNumberUniquenessViolated': true})),
first()); // important to make observable finite
}
事情可以简化一点
export class SomeAsyncValidator {
static createValidator = (someService: SomeService) => (control: AbstractControl) =>
timer(500)
.pipe(
map(() => control.value),
switchMap((name) => someService.exists({ name })),
map(() => ({ nameTaken: true })),
catchError(() => of(null)));
}
Angular 9+ asyncValidator w/ debounce
@n00dl3 有正确答案。我喜欢依靠 Angular 代码来取消订阅并通过抛出一个定时暂停来创建一个新的异步验证器。 Angular 和 RxJS API 自该答案撰写以来已经发展,因此我发布了一些更新的代码。
另外,我做了一些修改。 (1) 代码应报告已捕获的错误,而不是将其隐藏在电子邮件地址的匹配项下,否则我们会使用户感到困惑。如果网络故障,为什么说电子邮件匹配?! UI 表示代码将区分电子邮件冲突和网络错误。 (2) 验证器应该在时间延迟之前捕获控件的值,以防止任何可能的竞争条件。 (3) 使用 delay
而不是 timer
因为后者将每半秒触发一次,如果我们的网络速度较慢并且电子邮件检查需要很长时间(一秒),计时器将继续重新触发 switchMap 和通话永远不会完成。
Angular 9+ 兼容片段:
emailAvailableValidator(control: AbstractControl) {
return of(control.value).pipe(
delay(500),
switchMap((email) => this._service.checkEmail(email).pipe(
map(isAvail => isAvail ? null : { unavailable: true }),
catchError(err => { error: err }))));
}
PS:任何想要深入研究 Angular 来源的人(我强烈推荐),您可以找到运行异步验证的 Angular 代码 here and the code that cancels subscriptions here which calls into this .所有相同的文件都在 updateValueAndValidity
.
尝试使用计时器。
static verificarUsuario(usuarioService: UsuarioService) {
return (control: AbstractControl) => {
return timer(1000).pipe(
switchMap(()=>
usuarioService.buscar(control.value).pipe(
map( (res: Usuario) => {
console.log(res);
return Object.keys(res).length === 0? null : { mensaje: `El usuario ${control.value} ya existe` };
})
)
)
)
}
}
由于我们正试图减少我们向服务器发出的请求数量,我还建议添加一个检查以确保只将有效的电子邮件发送到服务器进行检查
我使用了 JavaScript: HTML Form - email validation
中的简单RegEx
我们还使用 timer(1000)
创建一个在 1 秒后执行的 Observable。
设置了这两项后,我们只检查电子邮件地址是否有效,并且仅在用户输入后 1 秒后检查。 switchMap
如果有新的请求,运营商将取消之前的请求
const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
const emailExists = control =>
timer(1000).pipe(
switchMap(() => {
if (emailRegExp.test(control.value)) {
return MyService.checkEmailExists(control.value);
}
return of(false);
}),
map(exists => (exists ? { emailExists: true } : null))
);
然后我们可以将此验证器与 Validator.pattern()
函数一起使用
myForm = this.fb.group({
email: [ "", { validators: [Validators.pattern(emailRegExp)], asyncValidators: [emailExists] }]
});