The idea is to get a data from another source in certain cases, so I have this stub:
factory("interceptor", function ($q, $location, $http) {
return function (promise) {
return promise;
}
}
which fails with
[$injector:cdep] Circular dependency found: interceptor <- $http
Also tried to inject $injector and retrieve $http using that, with same results. Any ideas?
.config is nothing but declaration:
.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('interceptor');
});
The diagram above shows that the HTTP interceptors will always be in the middle of any single HTTP request. These services will intercept all requests performed by the app, allowing us to perform many operations on them before they are sent to the server.
To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can:
A request interceptor is a piece of code that gets activated for every HTTP request sent and received by an application. It’s a layer in between clients and servers that modifies the request and responses, therefore, by intercepting the HTTP request, we can change the value of the request.
What Are Http Interceptors And How to Use Them In Angular? Use cases where we can make use of Interceptors in Angular. We have faced multiple scenarios where we might want to globally capture or change every request or response, like append a user’s token or handle errors from the response and we can achieve this using Http Interceptor.
$injector
to interceptor
:Use it to get $http
inside the returned object within callback functions.
Here is an example
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('interceptor');
});
app.factory("interceptor", function ($q, $location, $injector) {
return {
request: function(config){
var $http = $injector.get('$http');
console.dir($http);
return config;
}
}
});
app.run(function($http){
$http.get('/')
});
After reviewing the Angular source code the better answer is such. $http method is accessible without dependency injection so the trick is to NOT INJECT $http and to simply use it. Like such:
Right Way
retryModule = angular.module('retry-call', [])
# Do not inject $http
retryModule.factory 'RetryCall', ($q)->
# More object keys
'responseError': (response)=>
# Just use $http without injecting it
$http(response.config)
$q.reject(response)
retryModule.config ['$httpProvider', ($httpProvider)->
$httpProvider.interceptors.push('RetryCall');
]
Wrong Way
# Do not do it this way.
retryModule.factory 'RetryCall', ($q,$http)->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With