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

问题描述 投票:3回答:1

我想将文件上传到我的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);
}
html angular typescript firebase firebase-storage
1个回答
0
投票

当你做currentFileUpload: FileUpload;你没有提供任何价值,你只提供currentFileUpload的类型。价值仍将是undefined。要初始化,请将其设置为实例:

currentFileUpload: FileUpload = fileUploadInstance; // Get the instance somehow
© www.soinside.com 2019 - 2024. All rights reserved.