Angular ui-router $state.go 没有在解析中重定向 [英] Angular ui-router $state.go is not redirecting inside resolve

查看:15
本文介绍了Angular ui-router $state.go 没有在解析中重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 angularjs 应用程序中,我正在检查用户是否登陆登录页面并已通过身份验证,然后将他重定向到主页.

In my angularjs app, I am checking if user lands on landing page and is already authenticated, then redirect him to home page.

.state('landingpage', {
            abstract: "true",
            url: "/landingpage",
            templateUrl: "app/landingpage/landingpage.html",
            resolve: {
                AutoLoginCheck: ['$state', '$window', function ($state, $window) {

                    if($window.localStorage.access_token != null)
                    {
                        if($window.sessionStorage.access_token == null) {
                            $window.sessionStorage.access_token = $window.localStorage.access_token;
                        }
                        UserInfoService.SetUserAuthenticated(true);

                        // it is not redirecting
                        return $state.go('app.home');

                    }
                }]
            }
        })

问题在于,尽管所有解析代码都成功运行,但用户并没有被重定向到 app.home.有人能说出为什么会这样吗?

The problem is that though all the resolve code is successfully run, user is not getting redirected to app.home. Can someone tell why this happens?

注意:状态app"也有一个解析,它获取要在app.home"状态中显示的数据.

Note: The state 'app' also has a resolve in which it fetches the data to be displayed in 'app.home' state.

推荐答案

你的问题可以有两种解决方案

There can be two solutions to your problem

  • 首先,您可以发出一个事件,然后侦听器将处理您的状态转换.你可以在父控制器的任何地方实现监听器

  • Firstly you can emit an event and the listener will handle your state transition. You can implement the listener in anywhere in a parent controller

其次,您可以实现 $stateChangeStart 钩子并在那里检查您的重定向条件

Secondly you can implement the $stateChangeStart hook and check your redirection condition there

$rootScope.$on('$stateChangeStart', function (event, toState) {      
     if (toState.name === 'landingpage') {              
       if (!isAuthenticated()) { // Check if user allowed to transition                  
            event.preventDefault();   // Prevent migration to default state                  
            $state.go('home.dashboard');           
        }
      }
});

这篇关于Angular ui-router $state.go 没有在解析中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆