前端之家收集整理的这篇文章主要介绍了
Angularjs后接收钩或类似?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在从服务器返回响应后每次都
调用一个
函数,而不是在回调之后显式
调用它?
主要目的是我有一个通用的错误处理程序服务,我在每个请求的回调函数中调用,我想在某处指定它,它将被自动调用.
@H_
404_4@
我给了Gloopy一个
解决方案,但是,他引用的
other post在DOM和
拦截器定义的
函数中进行DOM操作.相反,我将启动微调器的逻辑移到了inter the的顶部,我在$rootScope中使用一个变量来控制微调器的隐藏/
显示.它似乎工作得很好,我相信是更加可测试.
<img ng-show="polling" src="images/ajax-loader.gif">
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