在angularjs中自动重定向页面

时间:2014-08-24 06:13:31

标签: ruby-on-rails angularjs

在angularjs项目中,我想当用户没有登录时,页面会自动重定向到登录页面。为此,当用户想要查看页面时,如果之前没有登录,我会通过以下代码从rails sever发送401

def failure
    render :status => 401, :json => { :success => false, :info => "Login Credentials Failed" }
  end

我在Chrome浏览器中收到了这个:

 GET http://localhost:3000/api/record.json 401 (Unauthorized) angular.min.js?body=1:81
(anonymous function) angular.min.js?body=1:81
t angular.min.js?body=1:76
f angular.min.js?body=1:74
I angular.min.js?body=1:102
I angular.min.js?body=1:102
(anonymous function) angular.min.js?body=1:103
h.$eval angular.min.js?body=1:114
h.$digest angular.min.js?body=1:111
h.$apply angular.min.js?body=1:115
t angular.min.js?body=1:75
y angular.min.js?body=1:79
x.onreadystatechange

我在angularjs控制器中有以下代码来重定向页面:

'use strict';

angular.module('app',['ngRoute', 'ngResource', 'sessionService', 'recordService'])
        .config(['$httpProvider', function($httpProvider){
            $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
            var interceptor = ['$location', '$rootScope', '$q', function($location, $rootScope, $q) {
                function success(response) {
                    return response
                };

                function error(response) {
                    if (response.status == 401) {
                        $rootScope.$broadcast('event:unauthorized');
                        $location.path('/users/login');
                        return response;
                    };
                    return $q.reject(response);
                };

                return function(promise) {
                    return promise.then(success, error);
                };
            }];

//            $httpProvider.responseInterceptors.push(interceptor);
            $httpProvider.interceptors.push(interceptor);
        }])
        .config(['$routeProvider',function($routeProvider, $locationProvider){
            $routeProvider
                    .when('/',               {controller: 'HomeCtrl',    templateUrl: '<%= asset_path('templates/index.html') %>'})
                    .when('/record',         {controller: 'RecordCtrl',  templateUrl: '<%= asset_path('templates/record/index.html') %>'})
                    .when('/users/login',    {controller: 'UsersCtrl',   templateUrl: '<%= asset_path('templates/users/login.html') %>'})
                    .when('/users/register', {controller: 'UsersCtrl',   templateUrl: '<%= asset_path('templates/users/register.html') %>'})
                    .otherwise(              {redirectTo: '/'});
        }]);

现在当我运行项目并且我想接受localhost:3000/#/record时,我看到没有数据的记录页面,页面没有重定向到登录页面。我该如何解决这个问题并解决它?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

angular.module('myapp')
    .factory('httpInterceptor', ['$q', '$location',function ($q, $location) {
        var canceller = $q.defer();
        return {
            'request': function(config) {
                // promise that should abort the request when resolved.
                config.timeout = canceller.promise;
                return config;
            },
            'response': function(response) {
                return response;
            },
            'responseError': function(rejection) {
                if (rejection.status === 401) {
                    canceller.resolve('Unauthorized'); 
                    $location.url('/user/signin');
                }
                if (rejection.status === 403) {
                    canceller.resolve('Forbidden');  
                    $location.url('/');
                }
                return $q.reject(rejection);
            }

        };
    }
    ])
    //Http Intercpetor to check auth failures for xhr requests
   .config(['$httpProvider',function($httpProvider) {
        $httpProvider.interceptors.push('httpInterceptor');
    }]);

比路线

.state('user_actions', {
            abstract: true,
            templateUrl: 'users/views/actions.html',
            resolve: {
                hasaccess: function(Sessions){
                    return Sessions.hasAccess('users');
                } 
            },
            controller:'UserParentActionsController'
        })
        .state('user_actions.create', {
            url: '/user/create',
            templateUrl: 'users/views/create.html',
            resolve: {
                groups: function(Groups){
                   return Groups.getList();
                }
            },
            controller:'UserCreateController'
        })