Shukla

Shukla

  • 72
  • 433
  • 50

this.data is always coming has ‘undefined’ file save in Angular

Nov 30 2023 5:30 AM

I am new to angular , I learned myself and implemented following code , but this.data is always shows as ‘undefined’.

 this.data is always coming has ‘undefined’ – Please let me know what mistake I am doing, 

Functionality of my code :-  It simple angular page where I upload the .csv file with 5 headers and some data in these columns in the file. After I click on upload same .csv file should be saved to server.

Below is my code, here I am passing filename and file content (in json format) to my .net webAPI, my webapi will syyave the file to server.
1) Please let me know why the this.data is always shows as undefined

2) To save the new file to server, what ever I have implemented is that correct approach ?

/*fileName = '';*/
  fileSelected = false;
  invalidFileType = false;
  file: File = null; // Variable to store file
  data: any;
  jsonData: any;
  displayError: boolean;
  errorText: string;
  responseData: any;

  @ViewChild('fileUpload') fileUpload: ElementRef;
  /*fileName = '';*/
  fileSelected = false;
  invalidFileType = false;
  file: File = null; // Variable to store file
  data: any;
  jsonData: any;
  displayError: boolean;
  errorText: string;
  responseData: any;

  @ViewChild('fileUpload') fileUpload: ElementRef;

  Reset(form) {
    this.fileUpload.nativeElement.value = "";
    console.log("Reset completed");
  }

  UploadFile(filevalue) {

    const reqbody = {
      filename: this.file.name,
      lines: JSON.stringify(this.data)
    };

    var route = "FileSave";
    this.dataService.post(reqbody, route).subscribe(
      (data: any[]) => {
        console.log("Response data: " + data);
        LoggerService.success(`File successfully uploaded to server`, true, false);
        this.responseData = data;
      },
      (error: Response) => {
        this.displayError = true;
        this.errorText = `Error saving API service ${error.status}`;
      });
  }

  onFileChange(event: any): void {
    this.file = event.target.files[0];

         this.fileSelected = true;
        this.invalidFileType = false;
        this.readFile();

  }

  readFile(): void {

    fileReader.onload = (e: any) => {
      const binaryString = e.target.result;
      console.log(binaryString);
      const workBook = XLSX.read(binaryString, { type: 'binary' });

      const workSheetName = workBook.SheetNames[0];
      const workSheet = workBook.Sheets[workSheetName];

      // Parse the Excel data into JSON format
      this.data = XLSX.utils.sheet_to_json(workSheet);
      console.log(this.data);
    }
  }
}