有没有办法在每次从服务器返回响应后调用函数而不在回调后显式调用它?
主要目的是我有一个通用的错误处理程序服务,我在每个请求的回调中调用它,我想在某处指定它,它应该自动调用.
Dan*_*yon 16
我给了Gloopy +1解决方案,然而,他引用的其他帖子在配置和拦截器中定义的函数中执行DOM操作.相反,我将启动微调器的逻辑移动到截取器的顶部,并使用变量$rootScope
来控制微调器的隐藏/显示.它似乎工作得很好,我相信更容易测试.
<img ng-show="polling" src="images/ajax-loader.gif">
Run Code Online (Sandbox Code Playgroud)
angular.module('myApp.services', ['ngResource']).
.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('myHttpInterceptor');
var spinnerFunction = function (data, headersGetter) {
return data;
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
})
//register the interceptor as a service, intercepts ALL angular ajax http calls
.factory('myHttpInterceptor', function ($q, $window, $rootScope) {
return function (promise) {
$rootScope.polling = true;
return promise.then(function (response) {
$rootScope.polling = false;
return response;
}, function (response) {
$rootScope.polling = false;
$rootScope.network_error = true;
return $q.reject(response);
});
};
})
// other code left out
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6154 次 |
最近记录: |