【发布时间】:2021-03-17 07:14:56
【问题描述】:
我尝试创建一个自定义验证器来验证我的数据库中是否存在序列号。 为此,自定义验证器必须调用 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 初学者有什么想法吗? 提前感谢您的帮助。
【问题讨论】:
标签: angular typescript angular-reactive-forms angular-custom-validators