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

Angular: wait for location.href to complete using $q.deffer

本文关键字:deffer 完成 使用 href 等待 location 角度      更新时间:2023-09-26

我正在尝试显示用户下载文件时的UI加载栏。下载文件代码已经工作,并且我已经使用 Angular 配置了一个 UI 进度指示器,因此只需将布尔值设置为 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();
        });
};
您可能

不想将页面重定向到 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;
})

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