我想将文件上传到我的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);
}
当你做currentFileUpload: FileUpload;
你没有提供任何价值,你只提供currentFileUpload
的类型。价值仍将是undefined
。要初始化,请将其设置为实例:
currentFileUpload: FileUpload = fileUploadInstance; // Get the instance somehow