首页 > 解决方案 > Angular 视频验证器不要等待

问题描述

我的视频验证器有问题。我并不总是工作。它有时会在测试之前响应“无效”。

这是文件选择事件:

onVideoPick(event: Event) {
    const file = (event.target as HTMLInputElement).files[0];
    console.log('Video picked');
    this.CreaLotForm.get('video').patchValue(file);
    this.CreaLotForm.get('video').updateValueAndValidity();
    const reader = new FileReader();
    var count = 0
    let IsValid =  this.CreaLotForm.get('video').valid;
    reader.onload = () => {
      while (this.CreaLotForm.get('video').status === 'PENDING') {
        console.log((this.CreaLotForm.get('video').status));
        this.errorMessage = "Checking...";
        count = count + 1;
        if (count === 100) { break };
      }
      if (this.CreaLotForm.get('video').valid) {

        this.videoPreview = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(file));
        this.errorMessage = "this video is OK";
        console.log('VID valid');
      } else {
        this.errorMessage = "Error upload video, please retry (Type .mp4 only)";
        console.log('VID validnot');
      }
    };
    reader.readAsDataURL(file);
  }

这是验证器代码

export const mimeTypeVid = (
  control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
  if ((typeof control.value) === 'string') {
    return of(null);
  }
  const file = control.value as File;
  const fileReader = new FileReader();
  const frObs = Observable.create(
    (observer: Observer<{ [key: string]: any }>) => {
      fileReader.addEventListener('loadend', () => {  
        let isValid = false;
         console.log('file type '+file.type);
        switch (file.type) {
          case 'video/mp4':
            isValid = true;         
            break;
          case 'video/mp4v-es':
            isValid = true;      
            break;
          default:
            isValid = false; 
            break;
        }
        console.log("Mime Vid Validators"+ isValid)
        if (isValid) {
          observer.next(null);
        } else {
          observer.next({ invalidMimeType: true });
        }
        observer.complete();
      });
      fileReader.readAsArrayBuffer(file);
    }
  );
  return frObs;
};

这在 80% 的情况下都有效,但有时您必须使用另一个文件更新文件选择才能使其正常工作。

因为它在浏览器控制台中响应:

VID 无效

文件类型视频/mp4

Mime Vid 验证器true

最好的选择是什么?放一个计时器?更改验证器?

谢谢你的帮助 :)

标签: angular

解决方案


推荐阅读