I encountered an issue with my CRUD application where uploaded files do not immediately appear on the page until I refresh it. The same problem occurs when trying to delete a file.
For deleting, I was able to fix it by subscribing to the onClose event on modal/popconfirm. However, I am facing difficulties in applying the same logic for other operations, such as converting the file to base64 format. Let me guide you through an example that works (onDelete) and then explain the code that is causing problems when adding a new file.
Working example: In this scenario, I subscribe to onClose and use removeFile to delete the file with the correct ID. This action takes place in the PARENT component, where I display the data. After the file deletion, I call getData() function to retrieve updated data without having to refresh the page.
openPopconfirm(event: Event, data: any) {
const target = event.target as HTMLElement;
this.popconfirmRef = this.popconfirmService.open(
PopconfirmDeleteComponent,
target,
{ position: 'bottom-left', data: { injectedData: data } }
);
this.popconfirmRef.onClose.subscribe(() => {
this.apiService.removeFile(data.IdMultimedia).subscribe(() => {
this.getData();
});
});
}
In the popconfirm (modal) component, I simply call this.popconfirmRef.close() to dismiss the popup.
Example, which I can't get working: The commented part in the code seems structured correctly, but I'm struggling to implement the right logic within this.modalRef.onClose.subscribe()
openModalImage() {
this.modalRef = this.modalService.open(UploadImageComponent);
/* this.modalRef.onClose.subscribe(() => {
this.apiService.uploadFiles(formData).subscribe(() => {
this.getData();
});
}); */
}
(The code functions properly, but requires a page refresh after uploading a file to see the changes) At present, in the child component, I perform the following actions:
// Transform file to base64
convertFile(file: File): Observable<string> {
const result = new ReplaySubject<string>(1);
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (event: any) =>
result.next(btoa(event.target.result.toString()));
return result;
}
// Transform file when selected via input field
onFileSelected(event: any) {
this.selectedFile = <File>event.target.files[0];
this.convertFile(this.selectedFile).subscribe((base64) => {
this.base64Output = base64;
});
this.fileOnHold = true;
}
// On click upload function
onUpload() {
this.data = {
fileName: this.selectedFile.name,
nadomestnoBesedilo: this.nadomestnoBesedilo,
};
const formData: any = {
IdProfilDelodajalca: this.IdProfilDelodajalca,
Tip: 2,
VsebinaBin: this.base64Output,
VsebinaTekst: this.nadomestnoBesedilo,
};
this.apiService.uploadFiles(formData).subscribe(() => {});
this.modalRef.close(true);
}
If additional HTML code is required, please let me know. Thank you for your assistance!