我尝试制作一个自定义验证器来验证我的数据库中是否存在序列号。为此,自定义验证器必须调用 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 初学者有什么想法吗?预先感谢您的帮助。