angularangular2-formsangular2-di

Access a service from a custom validator in Angular2


I need to access my custom http service from inside a static method, as example:

import {Control} from 'angular2/common';
import {HttpService} from './http.service';

class UsernameValidator {
    static usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}

How can I access a service in this case?


Solution

  • Another approach consists in returning a function. This way this function can have access to HttpService instance provided during creation:

    class UsernameValidator {
      static createUsernameExist(http:HttpService) {
        return (control: Control) => { 
          ... /* Access my HTTPservice here */
        }
      }
    }
    

    You can then use it like that:

    validator: UsernameValidator.createUsernameExist(this.httpService)