我想将文件上传到我的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);
}

答案 0 :(得分:0)
执行currentFileUpload: FileUpload;
时,您没有为其提供任何值,您只提供currentFileUpload
的类型。该值仍为undefined
。要初始化,请将其设置为实例:
currentFileUpload: FileUpload = fileUploadInstance; // Get the instance somehow