我正在尝试使用此链接上的大致配方创建 AngularJS 拦截器 - https://thinkster.io/interceptors
我的代码如下 -
<!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 函数中的代码仅在 factory.config.run 中的 $http.get(' http://127.0.0.1:8082/customURL.htm ') 调用被执行时运行。发出任何 HTTP 请求时,如何使代码运行?- 例如,当执行此页面上的 google 链接时 -
<a href="http://www.google.com">GOOGLE</a>