AngularJS: ui-router secured states

£可爱£侵袭症+ 提交于 2019-12-23 20:05:14

问题


I have one main controller for my app - AppCtrl and use ui-router. How can I make secured states?

$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){
    var authorization = toState.data.authorization;

    if(!Security.isAuthenticated() && authorization != false)
        $location.path('/login');
});

For example I want to make books and authors states secured, and login state not secured.

.state('login', {
                url: '/login',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: false
                }
            })
.state('books', {
                url: '/books',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: true
                }
            })
.state('authors', {
                url: '/authors',
                templateUrl: /**/,
                controller: /**/,
                data: {
                    authorization: true
                }
            })

Security.isAuthenticated() function returns boolean. When I open /books everything works perfectly, page are being redirected to /login, when after redirecting I open /authors, page loads and it's content are shown, but browser's url is /login, so page being redirected, but somehow it's content are shown.


回答1:


Figured out that I have to prevent opening next route, and go to login state. Made some changes and all works perfectly.

if (!Security.isAuthenticated() && authorization != false){
        event.preventDefault();
        $state.go('login');
    }


来源:https://stackoverflow.com/questions/22526024/angularjs-ui-router-secured-states

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!