angularjs - 在angularjs $ http中处理重定向

标签 angularjs redirect

我在应用程序中使用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从服务器获取数据。如果 session 到期,则服务器返回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,但随后我发现仅打印状态值(response.status)即可使angularjs返回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 - 在angularjs $ http中处理重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469249/

相关文章:

html - 如何在使用 css 网格时优化大量 ng-repeats

javascript - 如何通过使用 jquery 单击链接重定向来从其他页面选择/激活某些东西或 div?

reactjs - 在没有反应路由器的情况下以编程方式重定向到 URL

asp.net-mvc-4 - MVC4 Windows 身份验证重定向到帐户/登录

javascript - Uncaught ReferenceError : require is not defined

javascript - AngularJS - 将全屏背景颜色应用于部分

javascript - AngularJS - 空 <option> - 其他解决方案不起作用

jquery - 在企业应用程序中使用 angularJS 而不是(jquery + jqTemplate+jqValidationEngine+jqGrid)

php回调函数到下一页

javascript - 如何正确使用 React 路由器重定向?