Reputation: 1618
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?
Upvotes: 18
Views: 6612
Reputation: 6099
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
],
});
}
Upvotes: 1
Reputation: 202316
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)
Upvotes: 10
Reputation: 658047
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.
Upvotes: 3