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'
})
}