【发布时间】:2015-01-05 16:17:55
【问题描述】:
我的问题是this question 的更大更广泛的版本。我想拦截 AngularJS 函数内发出的 所有 http 请求。稍后我需要更改请求 URL 并将其传递给服务器..
我该怎么做?到目前为止,我已经使用 $httpProvider 和 $q 创建了一个拦截器,但我只能拦截 $http 请求而不是所有请求,即 如果有人点击我页面上的任何 href 链接等。我的拦截器代码是:-
// register the interceptor as a service
myModule.factory('myHttpInterceptor', function ($q) {
return {
// optional method
'request': function (config) {
// do something on success
console.log("request success");
return config;
},
// optional method
'requestError': function (rejection) {
// do something on error
console.log("Request Error");
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function (response) {
// do something on success
console.log("Response received");
return response;
},
// optional method
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
myModule.factory('myInterceptor', ['$log', function ($log) {
$log.debug('$log is here to show you that this is a regular factory with injection');
var myInterceptor = {
};
return myInterceptor;
}]);
myModule.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
}]);
【问题讨论】:
标签: javascript angularjs angularjs-routing