import { Observable } from 'rxjs/Observable' ; import { AbstractControl , ValidatorFn } from '@angular/forms' ; import { Injectable } from '@angular/core' ; import { UserService } from './../../core/services' ; @ Injectable ( ) export class AsyncFormValidatorsService { timeout : any ; debounceTime : number = 1000 ; constructor ( private us ) { } usernameUnique ( ) { return ( c ) : Observable < { [ key ] : any ; } > => { const username = c . value ; clearTimeout ( this . timeout ) ; return Observable . create ( ( observer ) => { this . timeout = setTimeout ( ( ) => { this . us . usernameIsUnique ( username ) . map ( isUnique => isUnique ? null : { isNotUnique : true } ) . subscribe ( res => { observer . next ( res ) ; observer . complete ( ) ; } ) ; } , this . debounceTime ) ; } ) ; } ; } }