may*_*ele 6 download save-as filesaver.js angular
我已经检查了所有可以找到使用Filesaver JS with angular的帖子,但我仍然无法绕过一个灵魂.我将其添加到system.config.js的map部分
'filesaver': 'node_modules/filesaver/src/Filesaver.js'
Run Code Online (Sandbox Code Playgroud)
我将它添加到system.config.js的packages部分
'filesaver': {defaultExtension: 'js'}
Run Code Online (Sandbox Code Playgroud)
然后我以这种方式将其导入我的service.ts.
import { saveAs } from 'filesaver';
Run Code Online (Sandbox Code Playgroud)
但是我得到了这个错误.
有人可以帮忙吗?
mak*_*asi 12
对于带有http的angular-cli(后跟httpClient):
npm install file-saver --save
Run Code Online (Sandbox Code Playgroud)
将此第三方lib添加到.angular-cli.json
"scripts": [
"../node_modules/file-saver/FileSaver.js"
],
Run Code Online (Sandbox Code Playgroud)
在blabla服务:
downloadBlaBlasCSV() {
let options = {responseType: ResponseContentType.ArrayBuffer };
return this.http.get(this.config.apiUrl + '/blablasCSV', options)
.catch((err: Response) => Observable.throw(err.json()));
}
Run Code Online (Sandbox Code Playgroud)
最后在组件中:
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);
}
Run Code Online (Sandbox Code Playgroud)
HttpClient的
它和http一样,但服务方法不同:
downloadBlaBlasCSV() {
return this.httpClient.get(this.config.apiUrl + '/blablasCSV', {
headers: new HttpHeaders().set('Accept', 'text/csv' ),
observe: 'response',
responseType: 'blob'
})
}
Run Code Online (Sandbox Code Playgroud)
请尝试以下方法
npm install file-saver --save
Run Code Online (Sandbox Code Playgroud)
然后在项目中添加一个声明文件,如'declarations.d.ts',然后放入其中
declare module 'file-saver';
Run Code Online (Sandbox Code Playgroud)
在systemjs.config.js中,将以下内容添加到地图部分
'file-saver': 'npm:file-saver/FileSaver.js'
Run Code Online (Sandbox Code Playgroud)
然后在您的组件或服务中导入库,如下所示
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')
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
21777 次 |
| 最近记录: |