Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

validation - How to debounce async validator in Angular 4 with RxJS observable?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While @Slava's answer is right. It is easier with Observable :

return (control: AbstractControl): Observable<ValidationErrors> => {
      return Observable.timer(this.debounceTime).switchMap(()=>{
        return this.usersRepository
            .emailExists(control.value)
            .map(result => (result ? { duplicateEmail: true } : null));
      });
}

updated with modern RxJS:

return (control: AbstractControl): Observable<ValidationErrors> => {
    return timer(this.debounceTime).pipe(
        switchMap(()=>this.usersRepository.emailExists(control.value)),
        map(result => (result ? { duplicateEmail: true } : null))
    );
}

Notes:

  • Angular will automatically unsubscribe the returned Observable
  • timer() with one argument will only emit one item
  • since timer emits only one value it does not matter if we use switchMap or flatMap
  • you should consider to use catchError in case that the server call fails
  • angular docs: async-validation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...