我尝试制作一个自定义验证器,用于验证数据库中是否存在序列号。为此,自定义验证器必须调用一个api端点。这是我的自定义验证器
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidator, FormControl } from '@angular/forms';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class HttpRequestValidation implements AsyncValidator {
constructor(private http: HttpClient) {}
validate = (control: AbstractControl) => {
const { value } = control;
console.log(value);
return this.http.get<any>(`http://127.0.0.1/backend/api-vitoapp/verify-serial.php?serial=${value}`)
.pipe(
map(() => {
return null;
}),
catchError((err) => {
console.log(err);
return of(true);
})
);
};
}
在我的组件中,我调用类似的验证器
deviceSelected : any;
serial = new FormControl('');
constructor(private fb: FormBuilder,
private hardwareCheckService: HardwareCheckService) {
}
ngOnInit() {
this.deviceInfos = this.fb.group({
serial: [null, [Validators.required, this.httpRequestValidation.validate]],
deviceType: [this. deviceTypeOptions[0]],
});
}
在我的模板中,我有这个
<mat-form-field *ngIf= "deviceSelected" fxFlex="auto">
<mat-label>Serial</mat-label>
<input formControlName="serial" matInput required>
</mat-form-field>
我不明白为什么我的连载总是被认为是未知的。对于Angular初学者有什么想法吗?提前感谢您的帮助。
使用FormBuilder时,异步验证器进入第二个数组:
serial: [null, [Validators.required], [this.httpRequestValidation.validate]],
此外,避免混合和匹配HTML验证和反应式表单。将required
从input
标签上取下:-(。