I have written an http interceptor to add authentication tokens to every request. In my html when i click a link this interceptor is not called. Not sure why that is happening?
My interceptor code -
angular.module('demo', [])
.factory('httpAuthorizationInterceptor',['$window', function ($window) {
return {
request: function (config) {
if (config.url.indexOf('login') == -1) {
config.headers['Authorization'] = 'Session ' +<session_id>;
}
return config || $q.when(config);
}
};
}])
My html -
<a data-ng-href="http://example.com/view"></a>
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response.
To implement an interceptor, you'll want to create a class that's injectable and that implements HttpInterceptor. The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent. req is the request object itself and is of type HTTP Request.
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
Your anchor tag will not actually make an ajax call, an http
interceptors are for intercepting ajax calls made via angular. Clicking on that anchor tag will be like opening an URL in the browser.
In order to do the ajax call: you need to tweak the code in the following way:
angular.module('demo', [])
.config(['$httpProvider', function ($httpProvider) {
var interceptor = [function() {
return {
'request': function(config) {
if (config.url.indexOf('login') == -1) {
config.headers['Authorization'] = 'Session ' + <session_id>;
}
return config;
}
};
}];
$httpProvider.interceptors.push(interceptor);
}]);
And now your controller code will look like something:
$scope.doSomething = function() {
$http({method: 'GET', url: 'http://example.com/view'}).then(function(data) {
// success
});
};
And your HTML code will be:
<a href="doSomething()"></a>
The only thing is that, the external url you are making ajax call is either be on the same domain or must support cross origin request.
Hope this helps!
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