Use Filesaver js with angular2
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'
})
}
Try the following
npm install file-saver --save
Then add a declarations file to your project like 'declarations.d.ts' and in it put
declare module 'file-saver';
In your systemjs.config.js, add the following to the map section
'file-saver': 'npm:file-saver/FileSaver.js'
And then import the library in your component or service like below
import { Component } from '@angular/core';
import * as saveAs from 'file-saver';
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<button (click)="SaveDemo()">Save File</button>`,
})
export class AppComponent {
name = 'Angular';
SaveDemo() {
let file = new Blob(['hello world'], { type: 'text/csv;charset=utf-8' });
saveAs(file, 'helloworld.csv')
}
}
Hope it helps.