When utilizing a service to upload images, I am encountering difficulty in retrieving the url
value that is set after the render.onload
event.
// custom image upload service
export class ImageUploadService {
constructor(private notificationService: NotificationService) {}
uploadImage(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg') {
const reader = new FileReader();
let url;
reader.onload = () => {
url = reader.result;
};
reader.onerror = (error: any) => {
this.notificationService.error(`Error loading image: ${error}`);
return;
};
reader.readAsDataURL(file);
return { File: file, Url: url };
} else {
this.notificationService.error('Invalid format. Only images in Png, Jpeg, and Jpg formats are allowed.');
return;
}
}
}
// component using the image upload service
uploadBanner(event: Event) {
const upload = this.imageUploadService.uploadImage(event);
if (upload) {
this.bannerUrl = upload.Url;
this.shop.banner = upload.File;
}
}
What is the best way to retrieve the values for url
and file
?