从状态提供程序的解析方法更改角度应用程序的状态 [英] Change state of angular app from resolve method of state provider

查看:23
本文介绍了从状态提供程序的解析方法更改角度应用程序的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 angular 应用程序中使用了 ui-router.目前我有两条路线/signin &/用户.最初,当用户单击登录按钮时,它会显示/signin,我正在发送一个 ajax 请求并获取用户 ID.我将用户 ID 存储在 localstorage 中并将状态更改为/user.

I'm using ui-router in my angular application. Currently I've two routes /signin & /user. Initially it shows /signin when the user clicks on the login button, I'm sending a ajax request and getting the user id. I'm storing the user id in localstorage and changing the state to /user.

现在,我想要的是,如果用户未登录,并且用户将地址栏更改为/user,它不会更改视图,而是再次将地址栏 url 更改为/signin.

Now, what I want, if a user is not loggedin, and user changes the addressbar to /user, it'll not change the view, instead it'll change the addressbar url to /signin again.

我正在尝试使用解析,但它不起作用.我的代码是:-

I'm try to use resolve, but it's not working. My code is:-

module.exports = function($stateProvider, $injector) {
$stateProvider
.state('signin', {
    url: '/signin',
    template: require('../templates/signin.html'),
    controller: 'LoginController'
})
.state('user', {
    url: '/user/:id',
    template: require('../templates/user.html'),
    resolve:{
        checkLogin:  function(){
             var $state = $injector.get('$state');
            console.log("in resolve");
             if (! window.localStorage.getItem('user-id')) {
                 console.log("in if")
                  $state.go('signin');
             }
        }
    },
    controller: 'UserController'
 })

}

请帮我解决这个问题.

推荐答案

我认为不允许在状态转换过程中改变状态.

I don't think it's allowed to change states in the middle of a state transition.

因此,解决它的方法是让 checkLogin 解析参数(我在下面将其更改为 userId)作为一个函数,该函数返回一个值或一个承诺(在这种情况下,拒绝的承诺,如果您无法获得 user-id).

So, the way to address it is to have the checkLogin resolve parameter (I changed it below to userId) to be a function that either returns a value or a promise (in this case, a rejected promise, if you can't get the user-id).

然后您需要在 $rootScope.$on('$stateChangeError') 中处理此问题并检查错误代码.

You'd then need to handle this in $rootScope.$on('$stateChangeError') and check the error code.

resolve: {
   userId: function ($q, $window) {
      var userId = $window.localStorage.getItem('user-id');
      if (!userId) {
         return $q.reject("signin")
      }

      return userId;
   }
}

并在 $stateChangeError 处理程序中重定向:

And redirect in the $stateChangeError handler:

$rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
     if (error === "signin") {
        $state.go("signin");
     }
});

这篇关于从状态提供程序的解析方法更改角度应用程序的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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