var value = await this.upload();
if (value == true) {
// Update item properties
this.item.photos = this.uploaded;
this.item.price = null;
this.item.qty = null;
// Add item to data service
this.dataSrv.addItem(this.item)
.then(() => {
this.dataSrv.stopLoading();
this.dataSrv.toast('Item Added Successfully');
// Reset item and picture arrays
this.item = {} as Item;
this.pictures = ['', '', '', ''];
this.uploaded = [];
this.photos = ['', '', '', ''];
})
.catch(err => {
this.dataSrv.stopLoading();
this.dataSrv.toast('Error While Adding Item. Try Again Later');
console.log(err);
});
}
The above code snippet demonstrates the process of uploading images to Google storage using the upload function. However, there seems to be an issue where the execution does not wait for the images to be uploaded before proceeding with the true condition.
async upload(image?) {
var counter = 0;
this.pictures.forEach(i => {
if (i != '') {
let temp: string = (i) as string;
// Process base64 image data
temp = temp.replace("data:image/jpg;base64, ", '');
temp = temp.replace("data:image/jpg;base64,", '');
temp = temp.replace('must use [property]=binding:', '');
temp = temp.replace('SafeValue', '');
temp = temp.replace('(see https://g.co/ng/security#xss)', '');
// Generate random ID for image
const randomId = Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36) + Math.random().toString(36);
// Upload image to storage
const uploadTask = this.storage.ref('items/').child(randomId).putString(temp, 'base64', {
contentType: 'image/png'
});
uploadTask
.then(response => {
console.log("uploaded");
console.log(response);
// Get download URL for uploaded image
this.storage.ref('items/' + randomId).getDownloadURL().subscribe(url => {
// Add URL to uploaded array
this.uploaded.push(url);
counter++;
});
})
.catch(err => {
console.log('not uploaded');
});
}
});
// Check if all images have been successfully uploaded
if (counter != this.uploaded.length) {
return false;
} else {
return true;
}
}
Attempts to resolve the issue by using Promise return type in the upload function or adding a then after the function call did not yield any changes. The pictures array contains base64 image data.