您的位置:首页 > Web前端 > AngularJS

angular2 下载保存文本数据

2017-09-05 02:37 253 查看
原文链接:http://blog.csdn.net/holdlg/article/details/54926136

需求

要导出API提供的数据,保存到本地。

思路

获取API数据。

使用Blob转化为文件对象。

创建一个a标签并加入dom,并设置相关参数,其中Blob会转化为链接。

触发a标签的 click 事件,然后销毁a标签。

源码

Service.ts

downloadService(): any {
let link = `${RootUrl}/data/all`;
return this.http.get(link)
.map(res => new Blob([res.text()],{ type: 'application/json' }))
.catch(this.handleError);
}


Component.ts

downloadComponent(): void {
var link = document.createElement("a");
this._listService.downloadService()
.subscribe(data => {
// Blob转化为链接
link.setAttribute("href", window.URL.createObjectURL(data));
link.setAttribute("download", 'filename.json');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
);
}


参考链接

http://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2

http://stackoverflow.com/questions/38793859/angular-2-downloading-a-file-corrupt-result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angular
相关文章推荐