以角度js下载文本文件的错误

时间:2018-04-03 08:24:37

标签: angularjs

我从后端下载了文本文件请求。我需要通过在service.js中发布get请求来下载文件,但问题是当我下载文件时,我得到%7d%7d为空。需要帮助。我甚至尝试过使用ng-href,但仍然没有运气

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

1 个答案:

答案 0 :(得分:1)

您的代码存在问题 $scope.newFile = service.downloadExhibitor();由于$http.getasync并且返回promise,您始终可以定义callback来处理success / error来自server的回复。

因此,当您的server返回response时,您没有定义任何操作来处理它。您的服务可以重写为: -

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

并最终service调用

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