保存在JSON要angularjs文件..? [英] Save json to file in angularjs..?
问题描述
我是新来angularjs,并试图建立一个单页的应用程序。我有一个家控制器非常简单code。它拥有一键式获取数据,它调用API和API返回JSON数据。
现在我得到的回应,我可以显示HTML页面的响应。
JSON数据是这样的。
{
名称:A,
时代:21
}
现在我的问题是
我如何保存上述JSON数据到PC,当我点击按钮获取数据?
$ scope.saveToPc =功能(数据,文件名){ 如果(!数据){
console.error(无数据);
返回;
} 如果(!文件名){
文件名='download.json';
} 如果(typeof运算数据==='对象'){
数据= JSON.stringify(数据,不确定,2);
} VAR BLOB =新的Blob([数据] {类型:'文/ JSON'}),
E = document.createEvent('MouseEvents'),
一个= document.createElement方法('一个'); a.download =文件名;
a.href = window.URL.createObjectURL(BLOB);
a.dataset.downloadurl = ['文/ JSON,a.download,a.href]。加入(':');
e.initEvent('点击',真,假窗,
0,0,0,0,0,假的,假的,假的,假的,0,NULL);
a.dispatchEvent(E);
};
该解决方案是无耻地从 http://bgrins.github.io/devtools复制-snippets /#控制台保存
修改
由于@ufk改变德precated方法 initMouseEvent
到 initEvent
。
不知道为什么它不MSIE 11的工作,可能是由于安全限制。而微软边缘有新的方式来设置人工事件的所有属性,但我没有测试过。
I am new to angularjs and trying create an single page application. I have a home controller with very simple code. It has one button "Get Data" which calls the api and api returns a json data.
Now I got the response and I can display the response on html page. The json data is like this
{
"Name":"A",
"Age":"21"
}
Now my problem is How can I save the above JSON data to pc when I click the button "Get Data" ?
$scope.saveToPc = function (data, filename) {
if (!data) {
console.error('No data');
return;
}
if (!filename) {
filename = 'download.json';
}
if (typeof data === 'object') {
data = JSON.stringify(data, undefined, 2);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
The solution is shamelessly copied from http://bgrins.github.io/devtools-snippets/#console-save
Edit
Thanks to @ufk changed deprecated method initMouseEvent
to initEvent
.
Don't know why it doesn't work in MSIE 11, probably due to security restrictions. And Microsoft Edge has new way to set all the properties of the synthetic event, but I haven't tested it.
这篇关于保存在JSON要angularjs文件..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!