Reputation: 63
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>
Upvotes: 6
Views: 4285
Reputation: 25797
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!
Upvotes: 3