$ http请求的后台处理通知

时间:2015-12-30 14:53:01

标签: javascript angularjs ajax angularjs-service

我正在寻找一种方法来包装"所有$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)

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

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

还有其他想法吗?

稍后修改

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

2 个答案:

答案 0 :(得分:2)

使用拦截器。请注意以下示例...

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 docs的拦截器部分以获取更多信息。

答案 1 :(得分:0)

我已成功设法使用AngularOverlay在http请求待处理时显示加载指示符。下载文件并按照说明进行操作。