【问题标题】:Unable to access global properties/methods inside jsZip.loadAsync()?无法访问 jsZip.loadAsync() 中的全局属性/方法?
【发布时间】:2023-02-20 19:41:56
【问题描述】:

有人可以解释为什么我无法访问 loadAsync() 中的全局变量吗?如何解决? 我正在尝试扫描我的 zip 文件,看看根目录中是否存在某些文件,如果存在,我想允许用户上传文件,否则会抛出错误消息,指出根 .csv 文件不存在”

我曾尝试将 rootFile 用作全局变量,但也无法访问它。

   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]);
}

【问题讨论】:

    标签: javascript angular typescript jszip


    【解决方案1】:

    this 在你的 function 中将引用函数范围。你可以更改你的代码以使用箭头函数而不是像

    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')
      }
    

    你可以阅读更多关于arrow function here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 2013-11-23
      相关资源
      最近更新 更多