0

我正在使用 Angular 反应式表单和异步验证,而不是正常值,我想发送 Json 文件进行验证。

我的表格看起来像

createGoogleCloudForm = new FormGroup(
{
  name: new FormControl('', [Validators.required, Validators.pattern(RegexUtil.cloudName)]),
  organizationId: new FormControl(''),
  config: new FormControl(),
  //zones: new FormControl({ value: '', disabled: true }, Validators.required),
},
undefined,

 //[GoogleCloudCredentialsValidator.checkGoogleCloudCredentials(this.cloudCredentialsCheckerService)]);

我的 HTML 文件看起来像

<form class="form" [formGroup]="createGoogleCloudForm" (ngSubmit)="createGoogleCloudCredential()">

  <div class="image-upload">
    <label for="background-upload" class="button button--outline display--inline-flex">Choose Config File</label>
    <span class="file-name">
      {{ googleCloudFormData?.get('config')?.name | truncate: 40:'...' 
  }}
  </span>
  <input
    type="file"
    id="background-upload"
    class="hidden-input"
    formControlName="config"
    (change)="fileChange($event.target.files, 'config')"
    />
  </div>
</div>

<div class="display--flex justify--content--end">
  <button class="button button--primary display--inline-flex" type="submit" [disabled]="!createGoogleCloudForm.valid">
    <svg-icon key="circle-plus"></svg-icon> Add Cloud Credentials
  </button>
</div>
</form>

文件更改方法就像

fileChange(files: File[], controlName: string) {
console.log(files);
if (files && files.length > 0) {
  this.googleCloudFormData.append(controlName, files[0]);
  console.log('adding');
  this.createGoogleCloudForm.setAsyncValidators([
    GoogleCloudCredentialsValidator.checkGoogleCloudCredentials(this.cloudCredentialsCheckerService),
  ]);
}
}

异步验证器是

static checkGoogleCloudCredentials(cloudCredentialsCheckerService: CloudCredentialsCheckerService): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> =>
  // half a second delay to prevent BE requesting after each user's key stroke
  timer(500).pipe(
    switchMap(() => cloudCredentialsCheckerService.checkGoogleCloud(control.get('config').value)),
    map(() => null),
    catchError(() => of({ invalidGoogleCloudCredentials: true })),
  );
}

和服务

checkGoogleCloud(file: File[]) {
  return this.http.post(`${this.baseUrl}/google`, { file });
}

问题是当我上传文件时,异步验证器不会被触发,我想随请求一起发送文件。

有任何想法吗?

4

0 回答 0