Angular JS $ locationChangeStart获取下一个url路由对象

Nir*_*han 10 authorization angularjs angularjs-routing

我正在尝试在我的角应用程序上实现授权,当路由被更改时我想检查路由是否被授权给用户.我尝试过,$routeChangeStart但它并没有阻止这个事件.

我目前的代码:

$scope.$on('$routeChangeStart', function(event, next, current) {
        if(current_user.is_logged_in){
            var route_object = next.route_object;
            if(!(route_object.route_roles)){
                event.preventDefault();
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

在我的next对象中,我得到了在我的设置中的route_object$routeProvider

var routes = object;
    app.config(function($routeProvider) {
                $routeProvider.when(url, {
                    templateUrl: "/users.html",
                    route_object: routes,
                    });
            });
Run Code Online (Sandbox Code Playgroud)

routes是一个在我的函数中形成的对象,但是当我使用时,$locationChangeStart我只是获取下一页和上一页的url,

我如何获得整个路径对象?

s.a*_*lem 18

您可以在$locationChangeStart事件侦听器中获取route参数,如下所示:

$scope.$on('$locationChangeStart', function(event, next, current) {
    if(current_user.is_logged_in){
        var route_object = ($route.routes[$location.path()]).route_object; //This is how you get it
        if(!(route_object.route_roles)){
            event.preventDefault();
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

那么经典的preventDefault方法就能完成这项工作.这是我为类似的东西写的一个傻瓜.

  • 这不起作用.如果$ location.path是/ user/10,则无法找到route/user /:id. (4认同)
  • 如果您使用的是ui.router,则需要使用$ stateChangeStart. (2认同)