根据条件重定向到某个路由

st.*_*ver 488 angularjs ngroute

我正在编写一个小型AngularJS应用程序,它具有登录视图和主视图,配置如下:

$routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
 .otherwise({redirectTo: '/login'});
Run Code Online (Sandbox Code Playgroud)

我的LoginController检查用户/传递组合并在$ rootScope上设置一个反映这个的属性:

function LoginController($scope, $location, $rootScope) {
 $scope.attemptLogin = function() {
   if ( $scope.username == $scope.password ) { // test
        $rootScope.loggedUser = $scope.username;
        $location.path( "/main" );
    } else {
        $scope.loginError = "Invalid user/pass.";
    }
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但如果我访问http://localhost/#/main我最终绕过登录屏幕.我想写一些类似"每当路由改变时,如果$ rootScope.loggedUser为null然后重定向到/ login"

...

......等一下 我能以某种方式听路线变化吗?无论如何我会发布这个问题并继续寻找.

st.*_*ver 505

经过一些文档和源代码的深入探讨后,我想我已经开始工作了.也许这会对其他人有用吗?

我在模块配置中添加了以下内容:

angular.module(...)
 .config( ['$routeProvider', function($routeProvider) {...}] )
 .run( function($rootScope, $location) {

    // register listener to watch route changes
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
      if ( $rootScope.loggedUser == null ) {
        // no logged user, we should be going to #login
        if ( next.templateUrl != "partials/login.html" ) {
          // not going to #login, we should redirect now
          $location.path( "/login" );
        }
      }         
    });
 })
Run Code Online (Sandbox Code Playgroud)

奇怪的是,我必须测试部分名称(login.html)因为"下一个"Route对象没有url或其他东西.也许有更好的方法?

  • 使用$ locationChangeStart而不是$ routeChangeStart来阻止路由被调用,并允许未经身份验证的用户查看他们无权访问的内容. (34认同)
  • 请记住,这是客户端.还应该存在服务器端障碍. (17认同)
  • 酷男,感谢您分享您的解决方案.有一点需要注意:在当前版本中,它是"next.$ route.templateUrl" (13认同)
  • 如果您在chrome检查器中查看网络请求,则仍会调用正在重定向的路由(因为用户未登录),并且会将响应发送到浏览器,然后调用重定向路径"/ login".因此,这种方法并不好,因为未登录的用户可以看到他们不应该访问的路由的响应. (5认同)
  • 如果并非所有路由都需要身份验证,则@sonicboom $ locationChangeStart没有意义,使用$ routeChangeStart,您可以在路由对象上拥有元数据,例如是否对其进行身份验证或该路由需要哪些角色.您的服务器应处理不显示未经身份验证的内容,并且AngularJS在路由更改之前不会开始处理,因此不应显示任何内容. (2认同)
  • 对我来说,$ routeChangeStart事件没有在$ rootScope上触发.我正在使用Ionic Framework 1.0.0-beta5.我不想使用$ locationChangeStart,因为它使用绝对URL.相反,我使用$ stateChangeStart运行良好,并在此处记录:https://github.com/angular-ui/ui-router/wiki#state-change-events (2认同)

Nik*_*pov 93

这可能是一个更优雅和灵活的解决方案,具有'resolve'配置属性和'promises',可根据数据在路由和路由规则上最终加载数据.

您在路由配置中的'resolve'中指定了一个函数,并在函数加载和检查数据中指定了所有重定向.如果您需要加载数据,则返回一个承诺,如果您需要重定向 - 在此之前拒绝承诺.所有细节都可以在$ routerProvider$ q文档页面上找到.

'use strict';

var app = angular.module('app', [])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: "login.html",
                controller: LoginController
            })
            .when('/private', {
                templateUrl: "private.html",
                controller: PrivateController,
                resolve: {
                    factory: checkRouting
                }
            })
            .when('/private/anotherpage', {
                templateUrl:"another-private.html",
                controller: AnotherPriveController,
                resolve: {
                    factory: checkRouting
                }
            })
            .otherwise({ redirectTo: '/' });
    }]);

var checkRouting= function ($q, $rootScope, $location) {
    if ($rootScope.userProfile) {
        return true;
    } else {
        var deferred = $q.defer();
        $http.post("/loadUserProfile", { userToken: "blah" })
            .success(function (response) {
                $rootScope.userProfile = response.userProfile;
                deferred.resolve(true);
            })
            .error(function () {
                deferred.reject();
                $location.path("/");
             });
        return deferred.promise;
    }
};
Run Code Online (Sandbox Code Playgroud)

对于讲俄语的人来说,有一篇关于" AngularJS " 的帖子"Вариантусловногораутинга" .


use*_*337 62

我一直在努力做同样的事情.在与同事合作之后,提出了另一个更简单的解决方案.我有一块手表$location.path().这就是诀窍.我刚刚开始学习AngularJS,发现它更清晰,更易读.

$scope.$watch(function() { return $location.path(); }, function(newValue, oldValue){  
    if ($scope.loggedIn == false && newValue != '/login'){  
            $location.path('/login');  
    }  
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为,如果给予否定投票,那么它应该有理由进行评论,这是公平的.它将有助于作为一种学习工具. (5认同)
  • 你在哪里设置手表? (3认同)
  • @freakTheMighty您必须在mainCtrl函数中设置监视,其中ng-controller设置为mainCtrl.例如<body ng-controller ="mainCtrl"> (3认同)

Ora*_*son 37

实现登录重定向的另一种方法是使用此处所述的事件和拦截器.本文介绍了一些其他优点,例如检测何时需要登录,对请求进行排队,以及在登录成功后重播它们.

你可以尝试了工作演示在这里和观看演示源在这里.

  • 您能否请更新此答案以包含链接中的相关信息?这样,即使链接断开,它仍将对访问者有用. (3认同)

AJc*_*dez 34

1.设置全局当前用户.

在身份验证服务中,在根范围上设置当前经过身份验证的用户.

// AuthService.js

  // auth successful
  $rootScope.user = user
Run Code Online (Sandbox Code Playgroud)

2.在每个受保护的路由上设置auth功能.

// AdminController.js

.config(function ($routeProvider) {
  $routeProvider.when('/admin', {
    controller: 'AdminController',
    auth: function (user) {
      return user && user.isAdmin
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

3.检查每次路线更改时的验证.

// index.js

.run(function ($rootScope, $location) {
  $rootScope.$on('$routeChangeStart', function (ev, next, curr) {
    if (next.$$route) {
      var user = $rootScope.user
      var auth = next.$$route.auth
      if (auth && !auth(user)) { $location.path('/') }
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

或者,您可以设置用户对象的权限并为每个路由分配权限,然后检查事件回调中的权限.

  • 我现在看到`$$ route`属性是Angular的*私有变量*.您不应该依赖它,例如:http://stackoverflow.com/a/19338518/1132101 - 如果这样做,您的代码可能会在Angular更改时中断. (2认同)
  • 我找到了一种方法来访问路由而无需访问私有属性或必须循环通过`$ route.routes`来构建一个列表(如在@ thataustin的答案中):使用`next.originalPath`获取该位置的路径并使用它来索引`$ route.routes`:`var auth = $ route.routes [next.originalPath]`. (2认同)

tha*_*tin 27

以下是我如何做到这一点,万一它可以帮助任何人:

在配置中,我publicAccess在我希望向公众开放的几条路线上设置了一个属性(如登录或注册):

$routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
    })
    .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        publicAccess: true
    })
Run Code Online (Sandbox Code Playgroud)

然后在运行块中,我在$routeChangeStart重定向到的事件上设置一个监听器,'/login'除非用户有权访问或路由是公共可访问的:

angular.module('myModule').run(function($rootScope, $location, user, $route) {

    var routesOpenToPublic = [];
    angular.forEach($route.routes, function(route, path) {
        // push route onto routesOpenToPublic if it has a truthy publicAccess value
        route.publicAccess && (routesOpenToPublic.push(path));
    });

    $rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
        var closedToPublic = (-1 === routesOpenToPublic.indexOf($location.path()));
        if(closedToPublic && !user.isLoggedIn()) {
            $location.path('/login');
        }
    });
})
Run Code Online (Sandbox Code Playgroud)

你显然可以将条件isLoggedIn改为其他任何东西......只是展示了另一种方法.


Chr*_*ong 9

我正在使用拦截器.我创建了一个库文件,可以将其添加到index.html文件中.这样,您将对其余服务调用进行全局错误处理,而不必单独关注所有错误.我还粘贴了我的basic-auth登录库.在那里你可以看到我也检查401错误并重定向到不同的位置.请参见lib/ea-basic-auth-login.js

LIB/HTTP的错误handling.js

/**
* @ngdoc overview
* @name http-error-handling
* @description
*
* Module that provides http error handling for apps.
*
* Usage:
* Hook the file in to your index.html: <script src="lib/http-error-handling.js"></script>
* Add <div class="messagesList" app-messages></div> to the index.html at the position you want to
* display the error messages.
*/
(function() {
'use strict';
angular.module('http-error-handling', [])
    .config(function($provide, $httpProvider, $compileProvider) {
        var elementsList = $();

        var showMessage = function(content, cl, time) {
            $('<div/>')
                .addClass(cl)
                .hide()
                .fadeIn('fast')
                .delay(time)
                .fadeOut('fast', function() { $(this).remove(); })
                .appendTo(elementsList)
                .text(content);
        };

        $httpProvider.responseInterceptors.push(function($timeout, $q) {
            return function(promise) {
                return promise.then(function(successResponse) {
                    if (successResponse.config.method.toUpperCase() != 'GET')
                        showMessage('Success', 'http-success-message', 5000);
                    return successResponse;

                }, function(errorResponse) {
                    switch (errorResponse.status) {
                        case 400:
                            showMessage(errorResponse.data.message, 'http-error-message', 6000);
                                }
                            }
                            break;
                        case 401:
                            showMessage('Wrong email or password', 'http-error-message', 6000);
                            break;
                        case 403:
                            showMessage('You don\'t have the right to do this', 'http-error-message', 6000);
                            break;
                        case 500:
                            showMessage('Server internal error: ' + errorResponse.data.message, 'http-error-message', 6000);
                            break;
                        default:
                            showMessage('Error ' + errorResponse.status + ': ' + errorResponse.data.message, 'http-error-message', 6000);
                    }
                    return $q.reject(errorResponse);
                });
            };
        });

        $compileProvider.directive('httpErrorMessages', function() {
            return {
                link: function(scope, element, attrs) {
                    elementsList.push($(element));
                }
            };
        });
    });
})();
Run Code Online (Sandbox Code Playgroud)

CSS/HTTP的错误handling.css

.http-error-message {
    background-color: #fbbcb1;
    border: 1px #e92d0c solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}

.http-error-validation-message {
    background-color: #fbbcb1;
    border: 1px #e92d0c solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}

http-success-message {
    background-color: #adfa9e;
    border: 1px #25ae09 solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}
Run Code Online (Sandbox Code Playgroud)

的index.html

<!doctype html>
<html lang="en" ng-app="cc">
    <head>
        <meta charset="utf-8">
        <title>yourapp</title>
        <link rel="stylesheet" href="css/http-error-handling.css"/>
    </head>
    <body>

<!-- Display top tab menu -->
<ul class="menu">
  <li><a href="#/user">Users</a></li>
  <li><a href="#/vendor">Vendors</a></li>
  <li><logout-link/></li>
</ul>

<!-- Display errors -->
<div class="http-error-messages" http-error-messages></div>

<!-- Display partial pages -->
<div ng-view></div>

<!-- Include all the js files. In production use min.js should be used -->
<script src="lib/angular114/angular.js"></script>
<script src="lib/angular114/angular-resource.js"></script>
<script src="lib/http-error-handling.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
Run Code Online (Sandbox Code Playgroud)

LIB/EA-基本认证 - login.js

登录几乎完全相同.在这里,您可以获得重定向的答案($ location.path("/ login")).

/**
* @ngdoc overview
* @name ea-basic-auth-login
* @description
*
* Module that provides http basic authentication for apps.
*
* Usage:
* Hook the file in to your index.html: <script src="lib/ea-basic-auth-login.js">  </script>
* Place <ea-login-form/> tag in to your html login page
* Place <ea-logout-link/> tag in to your html page where the user has to click to logout
*/
(function() {
'use strict';
angular.module('ea-basic-auth-login', ['ea-base64-login'])
    .config(['$httpProvider', function ($httpProvider) {
        var ea_basic_auth_login_interceptor = ['$location', '$q', function($location, $q) {
            function success(response) {
                return response;
            }

            function error(response) {
                if(response.status === 401) {
                    $location.path('/login');
                    return $q.reject(response);
                }
                else {
                    return $q.reject(response);
                }
            }

            return function(promise) {
                return promise.then(success, error);
            }
        }];
        $httpProvider.responseInterceptors.push(ea_basic_auth_login_interceptor);
    }])
    .controller('EALoginCtrl', ['$scope','$http','$location','EABase64Login', function($scope, $http, $location, EABase64Login) {
        $scope.login = function() {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + EABase64Login.encode($scope.email + ':' + $scope.password);
            $location.path("/user");
        };

        $scope.logout = function() {
            $http.defaults.headers.common['Authorization'] = undefined;
            $location.path("/login");
        };
    }])
    .directive('eaLoginForm', [function() {
        return {
            restrict:   'E',
            template:   '<div id="ea_login_container" ng-controller="EALoginCtrl">' +
                        '<form id="ea_login_form" name="ea_login_form" novalidate>' +
                        '<input id="ea_login_email_field" class="ea_login_field" type="text" name="email" ng-model="email" placeholder="E-Mail"/>' +
                        '<br/>' +
                        '<input id="ea_login_password_field" class="ea_login_field" type="password" name="password" ng-model="password" placeholder="Password"/>' +
                        '<br/>' +
                        '<button class="ea_login_button" ng-click="login()">Login</button>' +
                        '</form>' +
                        '</div>',
            replace: true
        };
    }])
    .directive('eaLogoutLink', [function() {
        return {
            restrict: 'E',
            template: '<a id="ea-logout-link" ng-controller="EALoginCtrl" ng-click="logout()">Logout</a>',
            replace: true
        }
    }]);

angular.module('ea-base64-login', []).
    factory('EABase64Login', function() {
        var keyStr = 'ABCDEFGHIJKLMNOP' +
            'QRSTUVWXYZabcdef' +
            'ghijklmnopqrstuv' +
            'wxyz0123456789+/' +
            '=';

        return {
            encode: function (input) {
                var output = "";
                var chr1, chr2, chr3 = "";
                var enc1, enc2, enc3, enc4 = "";
                var i = 0;

                do {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);

                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;

                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }

                    output = output +
                        keyStr.charAt(enc1) +
                        keyStr.charAt(enc2) +
                        keyStr.charAt(enc3) +
                        keyStr.charAt(enc4);
                    chr1 = chr2 = chr3 = "";
                    enc1 = enc2 = enc3 = enc4 = "";
                } while (i < input.length);

                return output;
            },

            decode: function (input) {
                var output = "";
                var chr1, chr2, chr3 = "";
                var enc1, enc2, enc3, enc4 = "";
                var i = 0;

                // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
                var base64test = /[^A-Za-z0-9\+\/\=]/g;
                if (base64test.exec(input)) {
                    alert("There were invalid base64 characters in the input text.\n" +
                        "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                        "Expect errors in decoding.");
                }
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

                do {
                    enc1 = keyStr.indexOf(input.charAt(i++));
                    enc2 = keyStr.indexOf(input.charAt(i++));
                    enc3 = keyStr.indexOf(input.charAt(i++));
                    enc4 = keyStr.indexOf(input.charAt(i++));

                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;

                    output = output + String.fromCharCode(chr1);

                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }

                    chr1 = chr2 = chr3 = "";
                    enc1 = enc2 = enc3 = enc4 = "";

                } while (i < input.length);

                return output;
            }
        };
    });
})();
Run Code Online (Sandbox Code Playgroud)

  • 除非你在指令中,否则你真的应该远离JS中的dom操作.如果您只是设置逻辑然后使用ng-class来应用类并触发CSS动画,您将在以后感谢自己. (2认同)

Ben*_*ane 7

在你的app.js文件中:

.run(["$rootScope", "$state", function($rootScope, $state) {

      $rootScope.$on('$locationChangeStart', function(event, next, current) {
        if (!$rootScope.loggedUser == null) {
          $state.go('home');
        }    
      });
}])
Run Code Online (Sandbox Code Playgroud)