0
我试图创建一个使用大致在这个环节中的配方AngularJS拦截 - https://thinkster.io/interceptorsAngularJS拦截器何时被调用?
我的代码如下 -
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
function tokenInterceptor() {
return {
request: function(config) {
config.xsrfHeaderName = 'myToken';
config.headers['myToken'] = "HelloWorld";
return config;
},
requestError: function(config) {
return config;
},
response: function(config) {
return config;
},
responseError: function(config) {
return config;
}
}
}
app
.factory('tokenInterceptor', tokenInterceptor)
.config(function($httpProvider) {
$httpProvider.interceptors.push('tokenInterceptor');
}).run(function($http) {
$http.get('http://127.0.0.1:8082/customURL.htm')
.then(function(res) {
console.log("get request to google");
});
});
</script>
<a href="http://www.google.com">GOOGLE</a>
</body>
</html>
tokenInterceptor函数内部的代码运行,只有当$ http.get(” http://127.0.0.1:8082/customURL.htm')在factory.config.run中的调用被执行。如何在发出HTTP请求时运行代码? - 例如,当谷歌这个页面上的链接执行 -
<a href="http://www.google.com">GOOGLE</a>
当一个请求作出的$ HTTP拦截器被调用通过角度$ http服务。指向谷歌的链接不会执行AJAX请求,甚至不会通过角度的$ http服务。 –