处理angularjs $http中的重定向

前端之家收集整理的这篇文章主要介绍了处理angularjs $http中的重定向前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中使用 angularjs http服务.我在 website发现了这个

If the AJAX call succeeds (the server sends back an HTTP code between
200 and 209),the function passed to the success() function is
executed. If the AJAX call fails (all other codes except for
redirects),the function passed to the error() method is executed.

显然,重定向状态代码不是成功的一部分,也不是错误回调.
那么我们如何处理重定向

这是我的脚本所做的,使用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
                }
            });
        };
});

显然,我的脚本不会工作,因为成功回调无法处理重定向.那么我们应该如何处理呢?

请注意,这是特定于我的项目.

目标:捕获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');
    }]);

猜你在找的Angularjs相关文章