How do I download a file with Angular2 or greater How do I download a file with Angular2 or greater javascript javascript

How do I download a file with Angular2 or greater


The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),                 error => console.log('Error downloading the file.'),                 () => console.info('OK');

When the request is ready it will call the function "downloadFile" that is defined as follows:

downloadFile(data: Response) {  const blob = new Blob([data], { type: 'text/csv' });  const url= window.URL.createObjectURL(blob);  window.open(url);}

the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;

  import 'rxjs/Rx' ;

I hope this can help you.


Try this!

1 - Install dependencies for show save/open file pop-up

npm install file-saver --savenpm install -D @types/file-saver

2- Create a service with this function to recive the data

downloadFile(id): Observable<Blob> {    let options = new RequestOptions({responseType: ResponseContentType.Blob });    return this.http.get(this._baseUrl + '/' + id, options)        .map(res => res.blob())        .catch(this.handleError)}

3- In the component parse the blob with 'file-saver'

import {saveAs as importedSaveAs} from "file-saver";  this.myService.downloadFile(this.id).subscribe(blob => {            importedSaveAs(blob, this.fileName);        }    )

This works for me!


If you don't need to add headers in the request, to download a file in Angular2 you can do a simple (KISS PRINCIPLE):

window.location.href='http://example.com/myuri/report?param=x';

in your component.