UI路由器不会让我回去解决状态
问题描述:
我想呼吁路线变化的服务,将检查接入和访问是否得到true
将打开路径,如果没有,会去设置路线UI路由器不会让我回去解决状态
app.js:
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'homeController',
resolve: {
access: function(AuthService) {
return AuthService.getAccess();
}
}
})
在我homeCtrl:
app.controller('homeController', function ($scope, $timeout, $state, UserService, GroupService, SiteService, HomeService, AuthService, access) {
// Check access: if true init route, else go to settings
if(access) {
Collections.init();
} else {
$state.go('settings');
}
});
如果我切换到没有任何解决另一种状态,我无法切换回主页,按钮只是d现在不做任何事情。
此外,而不是处理重新方向从homeCtrl设置,我将如何做到这一点的决心,那不是一种更好的方法
采用了棱角分明1.5.x版本和UI,路由器0.2 0.18
编辑:
我没有使用的决心,而是
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
AuthService.getAccess().then(function (access) {
if (!access && toState.name !== "settings") {
event.preventDefault();
toastr.warning('Your trial has expired');
$state.go('settings');
}
});
});
但是我注意到的是,我的UI将在someti加载之前mes在authService.getAccess()之前完成,所以我遇到了竞争条件。
我搬到了解决,因为这给了我在申请流程更好的控制。
答
另一种方法是什么你是 - 增加一个回调到每一个过渡的开始。
const app = angular.module('yourApplication');
app.run([
'$state', '$transitions', 'authManager',
function ($state, $transitions, authManager) {
$transitions.onStart({from: ''}, function (transition) {
const to = transition.$to();
const routeName = to.name;
if(!authManager.isAuthorizedRoute(routeName)) {
// here you can substitute login with any other state
// returning another target will break the transition and direct to another state
return transition.router.stateService.target('login');
}
// if nothing is returned the transition will continue
}
}
]);
编辑:
由于getAccess
执行异步 - 还有另一种解决方案:
1.创建一个父状态,把解决有你的决心
$stateProvider.state('authorized', {
resolve: {
access: function(AuthService) {
return AuthService.getAccess();
}
}
})
2.Define你的状态父状态
.state('yourSTATE', {
.....
parent: 'authorized',
....
})
周
的$转变3.Handle的onSuccess(https://github.com/angular-ui/ui-router/issues/2946)来访问解决数据,然后再决定是否转型成功应该和重定向到另一个目标
app.run([
'$transitions',
function ($transitions) {
$transitions.onSuccess({}, function(transition) {
var hasAccess = transition.getResolveValue('access');
if(!hasAccess) {
return transition.router.stateService.target('login');
}
});
}
]);
见我的编辑,我有过这样的事情,但我想比赛竞争条件。所以我转而解决,以确保在加载状态之前完成getAccess()。 – Batman
是的,因为'getAccess'异步工作,在这种情况下不起作用。我会编辑一个解决方案 –
@Batman,更新解决方案 - 请检查它并让我知道,无论它是否有帮助。 –