使用Günter Zöchbauer 的回答,这就是我实现验证器以从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
],
});
}