对于角度-CLI以http:
npm install file-saver --save
添加该第三方LIB到.angular-cli.json
"scripts": [
"../node_modules/file-saver/FileSaver.js"
],
在布拉布拉服务:
downloadBlaBlasCSV() {
let options = {responseType: ResponseContentType.ArrayBuffer };
return this.http.get(this.config.apiUrl + '/blablasCSV', options)
.catch((err: Response) => Observable.throw(err.json()));
}
最后整数组件:
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的
这就像HTTP,但服务的方法是不同的一样:
downloadBlaBlasCSV() {
return this.httpClient.get(this.config.apiUrl + '/blablasCSV', {
headers: new HttpHeaders().set('Accept', 'text/csv'),
observe: 'response',
responseType: 'blob'
})
}
由于它的工作。我首先导入了错误的库 –
@dipole:从文件保护程序github页面,它告诉我们一种安装typescript定义'npm install @ types/file-saver --save-dev'的方法。如上所述,我还需要添加声明文件吗?在我的项目根文件夹中,我有一个应用程序文件夹和其他文件,如systemjs.config.js文件。如果需要,我应该在哪里添加它?在应用程序文件夹内还是在项目根文件夹下? –
@ Ng2-Fun我无法使它与打字稿定义一起工作,这就是为什么我去了声明文件的路线。我一直得到“TypeError:file_saver_1.saveAs不是函数”。您可以将声明文件放在项目根文件夹中。 – dipole