use*_*598 20 redirect angularjs
我在我的应用程序中使用angularjs http服务.我在网站上注意到了这一点
如果AJAX调用成功(服务器发回200和209之间的HTTP代码),则执行传递给success()函数的函数.如果AJAX调用失败(除了重定向之外的所有其他代码),则执行传递给error()方法的函数.
显然,重定向状态代码不是成功的一部分,也不是错误回调.那么我们如何处理重定向?
这是我的脚本所做的,使用http get从服务器获取数据.如果会话到期,则服务器返回302状态代码.我应该抓住该状态代码然后将页面重定向到登录.
app.controller('GraphController', function($scope, $http, localStorageService, $interval) {
$scope.GraphData = [{"key":"in","values":[]},{"key":"out","values":[]}];
$scope.pollStats = function() {
$http.get('/statistics/getStat').success(function(lastData, status, headers) {
if (status==302) {
//this doesn't work
//window.location=headers('Location');
//this doesn't work either
window.location.replace(headers('Location'));
}else if (status==200) {
...processData
}
});
};
});
Run Code Online (Sandbox Code Playgroud)
显然我的脚本不会工作,因为成功回调无法处理重定向.那么我们该如何应对呢?
use*_*598 31
请注意,这是我的项目特有的.
目标:捕获302状态代码并重定向页面(在我的情况下登录).
结果:在firebug中,我可以看到响应代码是302,但后来我发现angularjs只需打印status(response.status)的值就返回200.所以起初你以为你没那么绝望了.但在我的情况下,我所做的是获取数据(response.data),查找只能在我的登录页面中找到的字符串.那就是它.问题解决了:D
这个想法是在这里采取的.
这是代码
app.factory('redirectInterceptor', function($q,$location,$window){
return {
'response':function(response){
if (typeof response.data === 'string' && response.data.indexOf("My Login Page")>-1) {
console.log("LOGIN!!");
console.log(response.data);
$window.location.href = "/login.html";
return $q.reject(response);
}else{
return response;
}
}
}
});
app.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('redirectInterceptor');
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51636 次 |
| 最近记录: |