I'm using custom async validator with Angular 4 reactive forms to check if E-Mail address is already taken by calling a backend.
However, Angular calls the validator, which makes request to the server for every entered character. This creates an unnecessary stress on the server.
Is it possible to elegantly debounce async calls using RxJS observable?
import {Observable} from 'rxjs/Observable';
import {AbstractControl, ValidationErrors} from '@angular/forms';
import {Injectable} from '@angular/core';
import {UsersRepository} from '../repositories/users.repository';
@Injectable()
export class DuplicateEmailValidator {
constructor (private usersRepository: UsersRepository) {
}
validate (control: AbstractControl): Observable<ValidationErrors> {
const email = control.value;
return this.usersRepository
.emailExists(email)
.map(result => (result ? { duplicateEmail: true } : null))
;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…