我编写了一个http拦截器来为每个请求添加身份验证令牌.在我的html中,当我点击链接时,不会调用此拦截器.不确定为什么会这样?
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); } }; }])
我的HTML –
<a data-ng-href="http://example.com/view"></a>
你的锚标签实际上不会进行ajax调用,http拦截器用于拦截通过angular进行的ajax调用.单击该锚标记就像在浏览器中打开URL一样.
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); }]);
现在您的控制器代码看起来像是:
$scope.doSomething = function() { $http({method: 'GET',url: 'http://example.com/view'}).then(function(data) { // success }); };
您的HTML代码将是:
<a href="doSomething()"></a>
唯一的问题是,您正在进行ajax调用的外部URL要么位于同一域,要么必须支持跨源请求.
希望这可以帮助!