Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as I have to update it in all three places. To tackle this problem, I have decided to create a service (non-shared) containing the method UploadFile(), which will allow me to make changes in one place only and be called by all three screens. However, I am facing a challenge regarding how to return alert messages and both success and failure responses from another service within this service back to the components.
@Injectable({
providedIn: 'root'
})
export class MyFileUploader {
fileuploadList: EventUpload[];
eventId: Number;
constructor(private dateFormatHelper: DateFormatHelper, private manageService: ManageService) {
}
public UploadFile(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file: File = fileList[0];
const extension = fileList[0].name.split('.').pop();
if (this.fileuploadList.find( f => f.fileName === file.name)) {
alert('Duplicate file identified!');
return;
}
const formData: FormData = new FormData();
const params = Object.assign({}, {
Id: 0,
F ileName: file.name,
FilePath: 'XXXXXX',
});
formData.append('uploadFile', file, params.FileName);
formData.append('data', JSON.stringify(params));
this.manageService.uploadAttachments(formData).subscribe (resp => {
if (resp === -1 ) {
alert('Error occured while uploading the attachment');
return;
} else {
this.fileuploadList.push (new DataUpload (0, params.FileName,
params.CreatedBy,));
}
},
(error) => {
console.log('POST ERROR in method uploadAttachments: ' + error.error);
}
);
}
}
}