从状态提供程序的解析方法更改角度应用程序的状态 [英] Change state of angular app from resolve method of state provider
问题描述
我在我的角度应用程序中使用ui-router.目前,我有两条路线/signin&/用户. 最初,当用户单击登录按钮时,它显示/signin,我正在发送ajax请求并获取用户ID.我将用户ID存储在本地存储中,并将状态更改为/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'
})
}
请帮助我解决这个问题.
Please help me to solve this problem.
推荐答案
我认为不允许在状态转换过程中更改状态.
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屋!