[英]Interceptor for all http requests in angularJS 1.0.x
我目前在一個有角度的應用程序工作,我想為我的應用程序的所有http請求編寫一個攔截器,它反過來調用一個服務來知道單點登錄會話是否仍然是活動的,如果它不活動我應該路由到我的單點登錄,然后提供用戶請求加載下一頁或結果。 我不確定如何在AngularJS中編寫攔截器,並且在我將頁面重定向到單點登錄時不確定如何保存用戶請求。
我目前正在使用angularjs 1.0.2,我看到1.0.2文檔中有responseInterceptors,但不是requestInterceptors。 。 是否有工作為Angular 1.0.2中的http調用編寫請求攔截器
在為當前穩定1.2.0工作的官方文檔中有一個很好的例子。
[ http://docs.angularjs.org/api/ng。$ http] [1](頁面頂部四分之一,搜索攔截器)
angular.module('RequestInterceptor', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('requestInterceptor');
})
.factory('requestInterceptor', function ($q, $rootScope) {
$rootScope.pendingRequests = 0;
return {
'request': function (config) {
$rootScope.pendingRequests++;
return config || $q.when(config);
},
'requestError': function(rejection) {
$rootScope.pendingRequests--;
return $q.reject(rejection);
},
'response': function(response) {
$rootScope.pendingRequests--;
return response || $q.when(response);
},
'responseError': function(rejection) {
$rootScope.pendingRequests--;
return $q.reject(rejection);
}
}
});
您可以存儲當前時間,而不是計數pendingRequests,也就是說lastRequestTimestamp。 如果將其與全局運行的計時器結合使用,則可以檢測上次請求的持續時間。
你可以很容易地使用攔截器
這是一個例子
var mydevices = angular.module('deviceDetails', ['ui.bootstrap', 'tags-input'])
mydevices.config(function ($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'request': function(config) {
if (config.method === 'GET' && config.url.contains("/rest/")) {
var sep = config.url.indexOf('?') === -1 ? '?' : '&';
config.url = config.url + sep + 'cacheSlayer=' + new Date().getTime();
}
console.log(config.url);
return config || $q.when(config);
}
};
});
});
上面的示例修改了所有/ rest / URL的URL
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.