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.

Leave a Comment