Angular:等待location.href使用$ q.deffer完成

时间:2016-03-21 12:10:10

标签: javascript angularjs download

我正在尝试显示用户下载文件时的UI加载栏。下载文件代码已经有效,我已经有一个配置了Angular的UI进度指示器,所以只需将bool值设置为true或false即可显示/删除进度条。我的代码如下所示:

$scope.getCompletedJobs = function () {

    $rootScope.blockUI = true;

    var params = {
        StartDate: $scope.StartDate,
        EndDate: $scope.EndDate
    };

    location.href = apiEntry.linkHref('get-completed-transfer-jobs') + "?" + $httpParamSerializer(params);

    $rootScope.blockUI = false;
};

我的问题很明显,location.href在执行后立即返回,导致$ rootScope.blockUI = false;执行,哪个有效$ rootScope.blockUI = false;只有当location.href完成时。我相信我需要使用某种deffer / promise模式,但我不完全确定如何使用Angular来实现它。

更新的答案

完成的工作代码现在看起来像这样

$scope.getCompletedJobs = function () {

    $rootScope.blockUI = true;

    var params = {
        StartDate: $scope.StartDate,
        EndDate: $scope.EndDate
    };

    $http.get(apiEntry.linkHref('get-completed-transfer-jobs') + "?" + $httpParamSerializer(params))
        .then(function (response) {
            //do something here with the response
            $rootScope.blockUI = false;

            var a = document.createElement('a');
            a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(response.data);
            a.target = '_blank';
            a.download = 'CompletedTransferJobs.csv';
            document.body.appendChild(a);
            a.click();
        });
};

2 个答案:

答案 0 :(得分:1)

 sertvicename.getData().then(function(data){
    //do what you want with data here
   //false logic come here after

   $rootScope.blockUI = false;      

 }).catch(fucntion(){

 //if any error 
 })

答案 1 :(得分:1)

您可能不想将网页重定向到api端点,而是在那里提出请求,

$scope.getCompletedJobs = function () {

        $rootScope.blockUI = true;

        var params = {
            StartDate: $scope.StartDate,
            EndDate: $scope.EndDate
        };

$http.get(apiEntry.linkHref('get-completed-transfer-jobs') + "?" + $httpParamSerializer(params)).then(function(response) {
//do something here with the response
 $rootScope.blockUI = true;
})



    };