$http请求的后台处理通知

background processing notification for $http requests

本文关键字:处理 通知 后台 http 请求      更新时间:2023-09-26

我正在寻找一种"包装"所有$http请求的方法,以便在应用程序进行某些处理时可以显示gif图像。我还想将相同的解决方案用于其他类型的背景处理,而不仅仅是$http

我之所以这么问,是因为我总是要将processingIndicator设置为true,然后切换回success函数,这一点都不优雅。

我看到的一个潜在的解决方案是使用一个将函数作为参数的函数。此函数将processingIndicator设置为true,调用该函数,然后将processingIndicator设置回`false。

function processAjaxRequestSuccessFn(fooFn){
  // display processing indicator
  fooFn();
  // hide processing indicator
}

然后

$http.get(...).then(processAjaxRequestSuccessFn, processAjaxRequestErrorFn)

这个解决方案不是很方便,因为每次我需要通知用户发生了什么事情,我都需要使用这个功能。

我正在寻找一种自动化这一过程的方法。

还有其他想法吗?

后期编辑

我的另一个想法是用我自己的getpost等扩展$http。或者创建一个具有类似行为的自定义服务。但仍然不是很优雅。

使用拦截器。观察以下示例。。。

app.factory('HttpInterceptor', ['$q', function ($q) {
    return {
        'request': function (config) {
            /*...*/
            return config || $q.when(config);   // -- start request/show gif
        },
        'requestError': function (rejection) {
            /*...*/
            return $q.reject(rejection);
        },
        'response': function (response) {       // -- end request/hide gif
            /*...*/
            return response || $q.when(response);
        },
        'responseError': function (rejection) {
            /*...*/
            return $q.reject(rejection);
        }
    };
}]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('HttpInterceptor');
    /*...*/
}]);

在这里,您可以在http请求生命周期的各个阶段注入集中式逻辑,挂接到api提供的回调中。制作您可能需要的任何可重复使用的请求逻辑-只需在这里完成即可。查看AngularJS$http文档的拦截器部分,了解更多信息。

我已经成功地使用AngularOverlay在http请求挂起时显示加载指示符。下载文件并按照说明操作,它应该可以工作。