要在Angular 5中使用自定义验证器调用服务方法,您需要按照以下步骤操作:
import { Injectable } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MyService } from './my.service';
@Injectable()
export class MyValidator {
constructor(private myService: MyService) {}
myCustomValidator(formGroup: FormGroup) {
const control = formGroup.controls['myControl'];
const value = control.value;
this.myService.myMethod(value).subscribe(
(result) => {
if (result.valid) {
control.setErrors(null);
} else {
control.setErrors({ 'invalid': true });
}
},
(error) => {
control.setErrors({ 'serverError': true });
}
);
}
}
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MyValidator } from './my-validator';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myForm: FormGroup;
constructor(private myValidator: MyValidator) {
this.myForm = new FormGroup({
myControl: new FormControl('', Validators.required)
});
}
onSubmit() {
// 执行自定义验证器
this.myValidator.myCustomValidator(this.myForm);
// 检查表单是否有效
if (this.myForm.valid) {
// 执行提交逻辑
// ...
}
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { MyService } from './my.service';
import { MyValidator } from './my-validator';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [AppComponent],
providers: [MyService, MyValidator],
bootstrap: [AppComponent]
})
export class AppModule {}
通过这些步骤,您就可以在Angular 5中使用自定义验证器调用服务方法了。