简体   繁体   中英

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?

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)
class UsernameValidator {
    constructor(http:HttpService){}

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

then use it like

validator: new UsernameValidator(http).usernameExist

The HttpService needs to be injected in the component constructor instead and then passed to the manually created validator instance as shown above.

Using Günter Zöchbauer's answer this is how I implemented my validator to access services from inside the AsyncValidatorFn ...

IMHO it seems cleaner to let the DI inject the service dependencies directly into the validator class instead of passing the dependencies to a static method from the consumer component to create the AsyncValidatorFn .

Create your injectable validator class

import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';

@Injectable
export class UsernameValidator {
  constructor(
    private http: HttpService,
  ) { }

  usernameExists: AsyncValidatorFn = (control: AbstractControl): Observable<ValidationErrors> => {
    // access your HttpService here...
  }
}

Provide validator for injection in your module declaration

@NgModule({
  providers: [
    UsernameValidator, // register your validator for injection
  ],
})
export class UserModule { }

Set validator function in your component form

constructor(
  private formBuilder: FormBuilder,
  private usernameValidator: UsernameValidator, // inject your validator
) { }

ngOnInit() {
  this.form = this.formBuilder.group({
    username: [
      null, // initial value
      [Validators.required], // sync validators
      [this.usernameValidator.usernameExists], // async validators
    ],
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM