Nicoleta Wilskon
Nicoleta Wilskon

Reputation: 697

Bug in downloading a text file in angular js

I have download text file request from backend. I need to download the file by posting get request given in service.js but the problem is I am getting %7d %7d in blank when I am downloading the file. Need assistance.I even tried with ng-href, still no luck

HTML:

<button class="btn btn-info" ng-click="downloadAllExhibitors();">
<a href="{{newFile}}" target="_blank">Download</a></button>

JS:

    $scope.downloadAllExhibitors = function () {
    $scope.newFile = service.downloadExhibitor(); 
     }

Service.js

   var url =' http://localhost/1290/';
  function downloadExhibitor() {


            var token = 129821sahh;
            var auth = "Token" + ' ' + token;

            var config = {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': auth
                }
            }

       return $http.get(url + 'entity/campaigns/download_exhibitors/', config);
        }

Upvotes: 0

Views: 61

Answers (1)

manish
manish

Reputation: 1458

The problem with your code lies in $scope.newFile = service.downloadExhibitor(); Since $http.get is async and returns a promise, you can always define callbacks to handle the success/error response from server.

So, by the time your server returns the response you have no actions defined to handle it. Your service can be re-written as :-

var url =' http://localhost/1290/';
function downloadExhibitor() {

        var token = 129821sahh;
        var auth = "Token" + ' ' + token;

        var config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': auth
            }
        }

        return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
               .then(successHandler, errorHandler);
}

function successHandler(response){
    /* we've got file's data from server */
    return response.data;
}

function errorHandler(error){
    /* we've got error response from server */
    throw new Error('ERROR ' + error);
}

and eventually the service invocation

$scope.newFile = "";
service.downloadExhibitor()
       .then(function(data){
                $scope.newFile = data;
             }, function(error){ 
                console.log(error);
             });

Upvotes: 1

Related Questions