I am using angular 13.0 and firebase 9.4. I want to upload multiple files to storage and build an array downloadURLs[]. Once all files are uploaded, I want to push the array to firestore. I am not able to capture the completion of all upload events with complete downloadURLs[]. Although all uploads are getting completed without any error.
My code is as below
//Code to upload a single file
private async uploadEachFile(fileToUpload: File, filePath: string): Promise<string> {
let downloadURL: string;
const storageRef = this.storage.ref(filePath);
const uploadTask = this.storage.upload(filePath, fileToUpload); //upload file
await uploadTask.snapshotChanges().pipe(
finalize(() => {
storageRef.getDownloadURL().subscribe(fileURL => {
downloadURL = fileURL;
return downloadURL;
});})).subscribe();
return downloadURL;
}
//Code to iterate all files
private addFilesToStorage(selectedFiles?: File[] ) {
let newFileName; //define file name
let filePath; //define file path
let downloadURLs: string[];
if(selectedFiles) {
const sfLastIndex = selectedFiles.length - 1;
for (let sfIndex = 0; sfIndex <= sfLastIndex; sfIndex++) { //iteration
const selectedFile = selectedFiles[sfIndex];
newFileName = selectedFile.name + '-' +
this.dateToString(new Date(),'yyMMddhhmmss');
filePath = 'images/' + newFileName;
this.uploadEachFile(selectedFile, filePath)
.then(downloadURL =>{
if(downloadURLs) {
downloadURLs.push(downloadURL);
} else {
downloadURLs = [downloadURL];
}
if(sfIndex === sfLastIndex) {
console.log(downloadURLs); // <- here NOT able to capture all URLs
pushURLsToFirestore(downloadURLs); //call a function to store an array
}
});
}
}