$ http请求的后台处理通知

tzo*_*zik 6 javascript ajax angularjs angularjs-service

我正在寻找一种"包装"所有$http请求的方法,这样我可以gif在应用程序进行某些处理时显示图像.我也希望将相同的解决方案用于其他类型的后台处理而不仅仅是$http.

为什么我问的原因是我总要为我设置processingIndicatortrue,然后我切换回success函数,而不是优雅的.

我看到的一个可能的解决方案是使用一个函数将函数作为参数.此函数将设置processingIndicatortrue,调用该函数,然后设置processingIndicator回"false".

function processAjaxRequestSuccessFn(fooFn){
  // display processing indicator
  fooFn();
  // hide processing indicator
}
Run Code Online (Sandbox Code Playgroud)

然后

$http.get(...).then(processAjaxRequestSuccessFn, processAjaxRequestErrorFn)
Run Code Online (Sandbox Code Playgroud)

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

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

还有其他想法吗?

稍后编辑

另一个想法我是延长$http我自己的get,post等等,或者创建具有类似行为的自定义服务.但仍然不是很优雅.

scn*_*iro 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);
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('HttpInterceptor');
    /*...*/
}]);
Run Code Online (Sandbox Code Playgroud)

在这里,您可以在 http 请求生命周期的各个点注入集中逻辑,挂钩到 api 提供的回调。制作您可能需要的任何可重用请求逻辑 - 只需在此处执行即可。查看AngularJS $http 文档的拦截器部分以获取更多信息。