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

编程入门 行业动态 更新时间:2024-10-08 02:24:57
本文介绍了Angular JS $locationChangeStart 获取下一个 url 路由对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在我的 angular 应用程序上实现授权,当路由更改时,我想检查该路由是否已为用户授权.我尝试使用 $routeChangeStart 但它不会阻止该事件.

I am trying to implement Authorization on my angular application, when a route is changed I want to check whether the route is authorized for user or not. I tried with $routeChangeStart but it does not prevents the event.

我当前的代码:

$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();
            }
        }
    });

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

Here in my next object I am getting route_object which is set in my $routeProvider

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

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

routes is an object which is formed in my function, but when I use $locationChangeStart I am just getting url's of next and previous page,

如何获取整个路由对象??

How do I get the entire route object??

推荐答案

您可以像这样在 $locationChangeStart 事件侦听器中获取路由参数:

You can get the route parameter in an $locationChangeStart event listener like this:

$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();
        }
    }
});

然后经典的 preventDefault 方法将完成这项工作.这是我为类似内容编写的 plunker.

Then classic preventDefault method would do the work. Here's a plunker that I wrote for something similar.

这篇关于Angular JS $locationChangeStart 获取下一个 url 路由对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 17:15:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007789.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   对象   JS   Angular   url

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!