[英]Download json using Angularjs
I have webapi returning me data and that data i need to download in a txt file. 我有webapi返回我的数据,我需要将这些数据下载到txt文件中。 I have done it using below code and i am getting result as desired.
我已经使用下面的代码来完成它,并且我正在根据需要获得结果。 I am somehow looking for a better approach .Is there any angular way to do this ?
我正在某种程度上寻找一种更好的方法。是否有任何角度的方法可以做到这一点?
$scope.downloadResponseAsInfoFile = function (response) {
var link = document.createElement("a");
link.download = "info.txt";
var data = "text/json;charset=utf-8," + encodeURIComponent(response);
link.href = "data:" + data;
link.click();
};
how can i handle exception in case i dont get response from server. 万一我没有收到服务器的响应,该如何处理异常。
In downloadResponseAsInfoFile
, if response is coming through http call than you need to handle exception according to response
. 在
downloadResponseAsInfoFile
,如果响应是通过http调用来的,则您需要根据response
处理异常。
$scope.downloadResponseAsInfoFile = function (response) {
// if this response is coming through http call than make condition according to http response.statusCode
//check response is undefined, null or empty
if(typeof response == 'undefined' || response == null || response == "")
return ;
var link = document.createElement("a");
link.download = "info.txt";
var data = "text/json;charset=utf-8," + encodeURIComponent(response);
link.href = "data:" + data;
link.click();
};
You can use angular's $http provider for fetching data from the web api See documentation here : - https://docs.angularjs.org/api/ng/service/ $http 您可以使用angular的$ http提供程序从Web api获取数据,请参阅此处的文档:-https: //docs.angularjs.org/api/ng/service/ $ http
$http.get(url).then(function (response) {
var link = document.createElement("a");
link.download = "info.txt";
var data = "text/json;charset=utf-8," + encodeURIComponent(response);
link.href = "data:" + data;
link.click();
};
You could try using native JavaScript API - Blob and FileSaver.js saveAs No need to deal with any HTML elements at all - 您可以尝试使用本机JavaScript API- Blob和FileSaver.js saveAs根本不需要处理任何HTML元素-
var data = {
key: 'value'
};
var fileName = 'myData.json';
// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
type: 'application/json',
name: fileName
});
// Save the file
saveAs(fileToSave, fileName);
Just paste the above code in your controller's callback. 只需将以上代码粘贴到控制器的回调中即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.