Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 基于用户cookie的ui路由器$state.go_Angularjs_Angular Ui Router - Fatal编程技术网

Angularjs 基于用户cookie的ui路由器$state.go

Angularjs 基于用户cookie的ui路由器$state.go,angularjs,angular-ui-router,Angularjs,Angular Ui Router,在使用ui路由器时,是否有方法根据cookie中的数据将用户重定向到特定状态 我试图从.config()中执行此操作,但由于无法注入其他依赖项,因此无法工作 我还尝试在.run()块上执行此操作,但它只是给出了一个循环(当然) 这是我第一次在.config() 有办法吗?还是以其他方式达到同样的效果?基本上,我需要根据用户角色将用户发送到应用程序的不同部分。如果他是管理员、客户、版主等。。每个都有一个特定的应用程序,需要从服务器检索特定的数据,这就是为什么我要这样做,这样我就可以请求每个状态的解

在使用
ui路由器时,是否有方法根据cookie中的数据将用户重定向到特定状态

我试图从
.config()
中执行此操作,但由于无法注入其他依赖项,因此无法工作

我还尝试在
.run()
块上执行此操作,但它只是给出了一个循环(当然)

这是我第一次在
.config()


有办法吗?还是以其他方式达到同样的效果?基本上,我需要根据用户角色将用户发送到应用程序的不同部分。如果他是管理员、客户、版主等。。每个都有一个特定的应用程序,需要从服务器检索特定的数据,这就是为什么我要这样做,这样我就可以请求每个状态的解析数据。

如果您使用的是angular ui router,您可以在顶部状态上使用
resolve
,在那里可以插入帮助您验证cookie的服务

您还可以拦截并在

.run(["$rootScope", "$location", "$state", "services.userService", function ($rootScope, $location, $state) {
        $rootScope.$on('$stateChangeStart', function (e, toState, toParams
            , fromState, fromParams) {
// validation
});
更多信息

还有这里的例子

ej:


我在.run部分进行了用户检查:

.run(['$rootScope', '$state', '$cookies',
    function ($rootScope, $state, $cookies) {
        if ($cookies.get('token'))
            $state.go('main');
        else
            $state.go('guest)
    }]);
当然,您应该在cookie中安装“token”。现在,您不需要在.config中使用$urlRouterProvider

    .state('main', {
                    templateUrl: 'app/modules/home/view.html',
                    abstract: true,
                    resolve: {
                        authorize: ['userService', "$state", "$q",  
                            function (userService, $state, $q) {
                                return checkAuthorization(userService, $state, $q)
                                    .then(function (user) {
                                        return {user: user}
                                    });
                            }]
                    },
                    controller: 'RootController'
                })
// more states

var checkAuthorization = function(userService, $state){
    //do all the necessary checks and return the user if he is already logged in
//redirecct to other page if the check failed
}
.run(['$rootScope', '$state', '$cookies',
    function ($rootScope, $state, $cookies) {
        if ($cookies.get('token'))
            $state.go('main');
        else
            $state.go('guest)
    }]);