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服務。 –