带有 http 的 Angular 自定义验证器不起作用

时间:2021-03-17 07:14:56

标签: angular typescript angular-reactive-forms angular-custom-validators

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

1 个答案:

答案 0 :(得分:1)

使用 FormBuilder 时,异步验证器进入第二个数组:

serial: [null, [Validators.required], [this.httpRequestValidation.validate]],

此外,避免混合和匹配 HTML 验证和响应式表单。去掉 required 标签上的 input :-).

相关问题