TypeError:无法读取未定义的属性“文件”

Posted

技术标签:

【中文标题】TypeError:无法读取未定义的属性“文件”【英文标题】:TypeError: Cannot read property 'File' of undefined 【发布时间】:2018-06-03 19:10:57 【问题描述】:

我想将文件上传到我的 firebase 存储并将 url 存储在数据库中。我遵循了我在此link 上找到的示例。我有两个不同的 ts 课程。当我点击提交按钮时,我的pushFileToStorage 函数出现了一个错误,上面写着TypeError: Cannot read property 'file' of undefined。谁能帮我解决这个问题?。

//these are from two different class files
//fileUpload.ts
export class FileUpload 
  name: string;
  Url: string;
  File: File;

  constructor(prdFile: File) 
    this.prdFile = prdFile;
  


//product.ts
export class Product 
  $prdKey: string;
  prdName: string;
  prdImage: string;
  prdDescription: string;

//product.service.ts

basePath = '/Product';
pushFileToStorage(fileUpload: FileUpload, Product: Product, progress: 
  percentage: number
) 
  const storageRef = firebase.storage().ref();
  const uploadTask = storageRef.child(`$this.basePath/$fileUpload.File.name`).put(fileUpload.File);

  uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
    (snapshot) => 
      // in progress
      const snap = snapshot as firebase.storage.UploadTaskSnapshot
      progress.percentage = Math.round((snap.bytesTransferred / snap.totalBytes) * 100)
    ,
    (error) => 
      // fail
      console.log(error)
    ,
    () => 
      // success
      this.productList.push(
        prdName: Product.prdName,
        prdImage: Product.prdImage = fileUpload.Url = uploadTask.snapshot.downloadURL,
        prdDescription: Product.prdDescription,
      )
      this.saveFileData(fileUpload)
    
  );


private saveFileData(fileUpload: FileUpload) 
  this.firebase.list(`$this.basePath/`).push(fileUpload);

//product.component.ts
currentFileUpload: FileUpload;
onSubmit(form: NgForm) 

  this.ProductService.pushFileToStorage(this.currentFileUpload, this.ProductService.selectedProduct, this.progress);

【问题讨论】:

你在product.component.ts文件中的哪里设置this.currentFileUpload属性? 喜欢这个currentFileUpload: FileUpload;CMIIW 【参考方案1】:

当您执行currentFileUpload: FileUpload; 时,您并没有为它提供任何值,您只是提供currentFileUpload 的类型。该值仍为undefined。将其初始化为实例:

currentFileUpload: FileUpload = fileUploadInstance; // Get the instance somehow

【讨论】:

以上是关于TypeError:无法读取未定义的属性“文件”的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法读取未定义的属性“分支”

TypeError:无法读取未定义的属性“getters”

(节点:47028)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“表情符号”

TypeError:无法读取未定义的属性(读取“名称”)

TypeError:无法读取未定义的属性“文件”

TypeError:无法使用 TSLint 和 TypeScript 读取未定义的属性“getFullWidth”