Search code examples
javascriptangulartypescriptjszip

Unable to access global properties/methods inside jsZip.loadAsync()?


can someone please explain why I am unable to access globals inside loadAsync()?How to fix it? I am trying to scan my zip file for if some files exist in root , if exists I want to allow user to upload file or else throw error message saying, root .csv file does not exist"

I have tried to use rootFile as global variable but cannot access it either.

   fileChange(e) {
    if (this.uploadAction) {
      this.scanfile(e);
     }
   

   scanfile(e) {
    var zip = new JSZip();
    zip.loadAsync(e.target.files[0]).then(function (zip) {
      let rootFile = [];
      for (let filename of Object.entries(zip.files)) {
        if (filename[0].match(/^[^/]+\.csv$/)) {
          rootFile.push(filename[0]);
        }
      }
      if (rootFile.length > 0) {
        this.uploadBlob(e); // error 
      } else {
        this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Root level .csv file is missing ' });  //error
      }
    }).catch((e) => console.log(e)) //Cannot read properties of undefined (reading 'uploadBlob')
  }

   uploadBlob(e) {
    console.log(e.target.files[0]);
}

Solution

  • this inside your function will refer to the function scope.You can change your code to use arrow function instead something like

    scanfile(e) {
        var zip = new JSZip();
        zip.loadAsync(e.target.files[0]).then((zip)=> { //use arrow function here
          let rootFile = [];
          for (let filename of Object.entries(zip.files)) {
            if (filename[0].match(/^[^/]+\.csv$/)) {
              rootFile.push(filename[0]);
            }
          }
          if (rootFile.length > 0) {
            this.uploadBlob(e); // error 
          } else {
            this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Root level .csv file is missing ' });  //error
          }
        }).catch((e) => console.log(e)) //Cannot read properties of undefined (reading 'uploadBlob')
      }
    

    You can read more about arrow function here