pankaj
pankaj

Reputation: 1060

Download json using Angularjs

I have webapi returning me data and that data i need to download in a txt file. 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.

Upvotes: 3

Views: 5192

Answers (3)

Gautham
Gautham

Reputation: 876

You could try using native JavaScript API - Blob and FileSaver.js saveAs No need to deal with any HTML elements at all -

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.

Upvotes: 0

Vibhu
Vibhu

Reputation: 546

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

$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();
};

Upvotes: 1

eigenharsha
eigenharsha

Reputation: 2231

In downloadResponseAsInfoFile, if response is coming through http call than you need to handle exception according to 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();
};

Angular Way: article

Upvotes: 5

Related Questions