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))
;
}
}
After studying some offered solutions with Observables I found them too complex and decided to use a solution with promises and timeouts. Although blunt, this solution is much simpler to comprehend:
Here, I'm converting existing observable to promise using
toPromise()
operator of RxJS. Factory function is used because we need a separate timer for each control.Please consider this a workaround. Other solutions, which actually use RxJS, are most welcome!
I think your method only delay, not debounce, then find the sample way to archive this result.
While @Slava's answer is right. It is easier with Observable :
As the returned
Observable
will get unsubscribed if a new value arrives, there is no need to manage the timeout by hand.If you want to implement it using RxJs,you can listen for valueChanges explicitly and apply async validator on it. For e.g.,considering you have reference ref to your abstractControl you can do,
UPDATE RxJS 6.0.0:
*RxJS 5.5.0
For everyone who is using RxJS ^5.5.0 for better tree shaking and pipeable operators