Use Filesaver js with angular2

mayowa ogundele picture mayowa ogundele · Nov 24, 2016 · Viewed 26.7k times · Source

i have checked all the post i can find on the use of Filesaver JS with angular, but i still could not wrap my head around a soution. I added this to the map section of my system.config.js

 'filesaver': 'node_modules/filesaver/src/Filesaver.js'

I added this to the packages section of the system.config.js

  'filesaver': {defaultExtension: 'js'}

I then imported it in my service.ts this way

import { saveAs } from 'filesaver';

Yet i get this error.

enter image description here

Can someone help please?

Answer

makkasi picture makkasi · Jun 4, 2017

For angular-cli with http (followed by httpClient):

npm install file-saver --save

Add this third party lib to .angular-cli.json

"scripts": [
      "../node_modules/file-saver/FileSaver.js"
    ],

In the blabla service:

downloadBlaBlasCSV() {
        let options = {responseType: ResponseContentType.ArrayBuffer };
        return this.http.get(this.config.apiUrl + '/blablasCSV', options)
        .catch((err: Response) => Observable.throw(err.json()));
    }

Finally int the component:

import { saveAs } from 'file-saver';

downloadBlaBlasCSV() {
    this.blablaService.downloadBlaBlasCSV().subscribe(
      (data) => { this.openFileForDownload(data); },
      (error: any) => {
        ...
      });
  }

openFileForDownload(data: Response) {
    //var blob = new Blob([data._body], { type: 'text/csv;charset=utf-8' });
    //saveAs(blob, 'Some.csv');
    let content_type = data.headers.get('Content-type');
    let x_filename = data.headers.get('x-filename');
    saveAs(data.blob(), x_filename);
  }

httpClient

It's the same like http but the service method is different:

downloadBlaBlasCSV() {
        return this.httpClient.get(this.config.apiUrl + '/blablasCSV',  {
            headers: new HttpHeaders().set('Accept', 'text/csv' ),
            observe: 'response',
            responseType: 'blob'
        })
    }