typescript 错误类型错误:无法读取未定义的属性(正在读取"file")

svdrlsy4  于 2023-02-13  发布在  TypeScript
关注(0)|答案(1)|浏览(183)

我使用自定义验证创建了此组件,并在组件顶部声明变量并将值分配给,但当我在自定义验证中使用此变量时,如果以“ERROR TypeError:无法读取自定义验证扩展文件中未定义(阅读“文件”)”的属性,我必须声明并为内部变量赋值,所以我想知道原因是自定义验证功能未遵守,因此它在其他功能之前执行?,但为什么变量值不存在并赋值给未定义,以及如何在验证文件大小时使用文件大小?在所有情况下,这是组件代码

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { PagedResult } from 'src/app/core/models/pagedResult.model';
import { AlertService } from 'src/app/core/services/alert.service';
import { FakeDataService } from 'src/app/core/services/fake-data.service';
import { Employee } from '../../models/employee.model';
import { PenaltyReason } from '../../models/penalty-reason.model';
import { PenaltyType } from '../../models/penalty-type.model';
import { Penalty } from '../../models/penalty.model';

@Component({
  selector: 'app-penalties',
  templateUrl: './penalties.component.html',
  styleUrls: ['./penalties.component.css']
})
export class PenaltiesComponent implements OnInit {

  penalties: PagedResult<Penalty>;
  page = 1;
  formTitle = "اضافة عقوبة";
  penaltyTypes: PenaltyType[];
  penaltyReasons: PenaltyReason[];
  employees: Employee[];
  selectedPenaltyIndex: number;
  penaltyForm: FormGroup;
  file: FormControl;

  constructor(private fakeData: FakeDataService, private alert: AlertService) { }

  loadData() {
    this.fakeData.getDataFor('Penalties', this.page).then(result => {
      this.penalties = result as PagedResult<Penalty>;
    });
  }

  loadRequiredData() {
    //load penalty Types
    this.fakeData.getAllDataFor('PenaltyTypes').then(result => {
      this.penaltyTypes = result as PenaltyType[];
    });

    // Loading penalty Reasons
    this.fakeData.getAllDataFor('penaltyReasons').then(result => {
      this.penaltyReasons = result as PenaltyReason[];
    });

    // Loading Employees list
    this.fakeData.getAllDataFor('Employees').then(result => {
      this.employees = result as Employee[];
    });
  }

  ngOnInit(): void {
    this.resetForm();
    this.loadData();
    this.loadRequiredData();
  }

  paginateData(page: number) {
    this.page = page;
    this.loadData();
  }

  showEditForm(id: number, index: number) {
    var penalty2Edit = this.penalties?.data?.find(p => p.Id == id) as Penalty;
    this.penaltyForm?.setValue({ ...penalty2Edit });
    this.selectedPenaltyIndex = index;
  }

  delete(id: number) {
    var itemIndex = this.penalties.data.findIndex(c => c.Id == id);
    this.penalties.data.splice(itemIndex, 1);

    this.alert.showSuccess('تم مسح العنصر بنجاح');
  }

  resetForm() {
    this.file = new FormControl(null);
    this.penaltyForm = new FormGroup({
      Id: new FormControl(0),
      FingerPrintId: new FormControl(0),
      EmpId: new FormControl(0),
      EmpName: new FormControl('', Validators.required),
      Date: new FormControl('', Validators.required),
      PenalityTypeId: new FormControl(0),
      PenalityTypeText: new FormControl('', Validators.required),
      DeductionDaysCount: new FormControl(0, Validators.required),
      ReasonTypeId: new FormControl(0, Validators.required),
      DisciplineNotes: new FormControl('', Validators.required),
      ImageURL: new FormControl('', [this.ValidateExtentionFile, this.validateFileSize])
    });
    this.loadRequiredData();
  }

  addPenalty() {
    this.penaltyForm.get('Id')?.setValue(Math.floor(Math.random() * 1000));

    this.penalties.data.unshift(this.penaltyForm.value);
    this.resetForm();
    this.alert.showSuccess("تم إضافةالعقوبة بنجاح");
  }

  updatePenalty() {
    this.penalties.data.splice(this.selectedPenaltyIndex, 1, this.penaltyForm.value);
    this.alert.showSuccess('تم تعديل العنصر بنجاح');
  }

  // deal with file
  onFileSelected(event: any) {
    this.file.setValue(event.target.files[0]);
    console.log(this.file);
  }

  ValidateExtentionFile(control: AbstractControl): ValidationErrors | null {

    if (!control.value)
      return null;

    let allowedEXT = ['jpg', 'png', 'pdf', 'jpeg'];
    var fileExt = control.value?.split('.').pop().toLowerCase();

    if (allowedEXT.includes(fileExt))
      return null;

    return { valideFileEXT: true };
  }

  validateFileSize(control: AbstractControl): ValidationErrors | null {

    let maxSize = 1;

    if (!control.value || !this.file)
      return null;

    const fileSize = (this.file.value.size / 1024 / 1024); // convert to MB

    if (fileSize > maxSize) {
      return { 'validateFileSize': true };
    }
    return null;
  }

}
vngu2lb8

vngu2lb81#

你可以像这样
在组件文件中:

handleFileInput(files: any) {
    this.fileNameDetail = undefined;
    const image = files.files.item(0);
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      this.imageUrl = reader.result;
    }, false);
    reader.readAsDataURL(image);
  }

在模板文件中:

<button (click)="filePicker.click()" class="file-picker-opener">انتخاب فایل</button>
  <input type="file"
         class="form-control"
         #filePicker
         accept="image/jpeg,image/jpg"
         id="file"
         (change)="handleFileInput($event.target);"
  />

相关问题