Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import { AbstractControl } from "@angular/forms";
  2. import { Observable } from "rxjs/Observable";
  3. import { Subject } from "rxjs/Subject";
  4.  
  5. export class QstAsyncValidatorWrapper {
  6.  
  7. /*
  8. * Angular async validators are triggered on every key stroke.
  9. * This function debounces triggering an async validator.
  10. *
  11. * How to use?
  12. * Let's say you have a function which asynchronously validates an email:
  13. *
  14. * function asyncEmailValidator (c: AbstractControl): Observable<any> {
  15. * return checkInRemote();
  16. * }
  17. *
  18. * In your Reactive Form Builder instead of doing this:
  19. *
  20. * email: new FormControl("", [
  21. * Validators.required
  22. * ], [
  23. * asyncEmailValidator
  24. * ])
  25. *
  26. * Do this to debounce every 800ms:
  27. *
  28. * email: new FormControl("", [
  29. * Validators.required
  30. * ], [
  31. * QstAsyncValidatorWrapper.debounce(asyncEmailValidator, 800)
  32. * ])
  33. *
  34. *
  35. *
  36. * */
  37. public static debounce(asyncValidator: (c: AbstractControl) => Observable<any>,
  38. time: number = 500): (c: AbstractControl) => Observable<any> {
  39. /*Starting a debouncing observable*/
  40. const subject: Subject<AbstractControl> = new Subject();
  41.  
  42. const obs: Observable<any> = subject
  43. .debounceTime(time)
  44. .switchMap(abstractControl => asyncValidator(abstractControl))
  45. .do(item => console.log(item))
  46. .share();
  47.  
  48. return (c: AbstractControl) => {
  49. /*Every time this function is invoked by Angular I must inform a subject about it*/
  50. subject.next(c);
  51.  
  52. /*Need to take only one for every function invocation,
  53. * because the subscription must complete.
  54. * Otherwise Angular form state would be "PENDING"*/
  55. return obs.first();
  56. };
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement