I need to call a REST service that returns base64 encoded CSV files in a for loop. I then decode and concatenate these files into one string before returning it. However, when I try to subscribe to this method and download the file by clicking the DOM, I only get an empty string with "\r\n"
in it. Why doesn't it wait for the REST service to return the file before proceeding?
downloadFilesAndConcatenate(): Observable<any> {
let concatenatedFileDecoded: string = '\r\n';
for (let i = 0; i < this.fileIDs.length; i++) {
this.restService.getFile(this.fileIDs[i]).subscribe(response => {
this.fileResultSet = response;
this.message = response.message;
this.file = this.fileResultSet.result;
let fileCSVbase64 = this.file.fileBytes
let fileCSVDecoded = atob(fileCSVbase64);
concatenatedFileDecoded += fileCSVDecoded;
},
error => {
this.message = error.error.message;
});
return new Observable( observer => {
observer.next(concatenatedFileDecoded)
observer.complete();
});
}
}
Afterwards, I attempt to subscribe to it:
download() {
if (this.dateEnd !== null && typeof this.dateEnd !== "undefined") {
debugger;
this.downloadFilesAndConcatenate() // Multiple files
.subscribe(
(result) => {
debugger;
const link = document.createElement( 'a' );
link.style.display = 'none';
document.body.appendChild( link );
const blob = new Blob([result], {type: 'text/csv'});
const objectURL = URL.createObjectURL(blob);
link.href = objectURL;
link.href = URL.createObjectURL(blob);
link.download = this.file.name;
link.click();
},
(err) => {
console.error(err);
},
() => console.log("download observable complete")
);
} else {
this.downloadFile(); // Only one file
}
}