As Alejandro Corredor mentioned , this is a simple scale error. subscribe asynchronous, and open must be placed in this context for the data to finish loading when the download starts.
However, there are two ways to do this. Since the documents recommend that the service take care of the receipt and display of data:
//On the service: downloadfile(runname: string, type: string){ var headers = new Headers(); headers.append('responseType', 'arraybuffer'); return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type) .map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })) .catch(this.logAndPassOn); }
Then, on the component, we simply subscribe and process the displayed data. There are two possibilities. The first , as suggested in the original publication, but needs a little correction, as Alejandro noted:
//On the component downloadfile(type: string){ this.pservice.downloadfile(this.rundata.name, type) .subscribe(data => window.open(window.URL.createObjectURL(data)), error => console.log("Error downloading the file."), () => console.log('Completed file download.')); }
The second way is to use FileReader. The logic is the same, but we can clearly expect FileReader to load the data, avoiding nesting and solving the async problem.
//On the component using FileReader downloadfile(type: string){ var reader = new FileReader(); this.pservice.downloadfile(this.rundata.name, type) .subscribe(res => reader.readAsDataURL(res), error => console.log("Error downloading the file."), () => console.log('Completed file download.')); reader.onloadend = function (e) { window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no'); } }
Note. I am trying to download an Excel file, and even though the download has been initiated (so that answers the question), the file is damaged. See the answer to this post to avoid a damaged file.