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?
To validate required fields, for example, we can use the built-in required validator on template-driven forms by adding the required attribute. const control = new FormControl('', Validators. required); Those validators are very helpful because they allow us to perform standard form validation.
A validator in Angular is a function which returns null if a control is valid or an error object if it's invalid. For model-driven forms we create custom validation functions and pass them into the FormControl constructor.
Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With