Angular ui-router:如何推迟渲染模板直到授权完成? [英] Angular ui-router: How to defer rendering the template until authorization is complete?
问题描述
我的 ui-router 配置是这样的:
My ui-router configuration is this:
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'sidemenu/sidemenu.html',
controller: 'SideMenuCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'login/login.html',
controller: 'LoginCtrl'
})
.state('app.dashboard', {
url: '/dashboard',
views: {
menuContent: {
templateUrl: 'dashboard/dashboard.html',
controller: 'DashboardCtrl'
}
}
})
[More states here]
$urlRouterProvider.otherwise('/app/dashboard');
当用户导航到 /app/dashboard
我想检查他们是否被授权,然后:
When user navigates to /app/dashboard
I would like to check if they are authorized, and then:
- 重定向到
/login
如果他们没有被授权,或者 - 如果他们获得授权,则允许查看仪表板
- redirect to
/login
if they are not authorized, or - allow to see the dashboard if they are authorized
这似乎可以解决问题:(基于 这个例子)
This seems to do the trick: (based on this example)
$rootScope.$on('$stateChangeSuccess', function(event) {
var path = $location.path();
if (path === '/login') {
return;
}
// Halt state change from even starting
event.preventDefault();
Auth.getCurrentUser().then(function(currentUser) {
if (currentUser === null) {
$state.go('login');
} else {
// Continue with the update and state transition
$urlRouter.sync();
}
});
});
此解决方案的唯一问题是,如果非授权用户导航到仪表板,仪表板模板首先可见.只有当授权响应返回时,它才会更改为登录模板.
The only problem with this solution is that, if a non-authorized user navigates to the dashboard, the dashboard template is visible first. Only when the authorization response is coming back it changes to the login template.
有没有办法在我们授权用户时不显示仪表板?
Is there a way not to show the dashboard while we authorize the user?
我也尝试将 $stateChangeSuccess
更改为 $stateChangeStart
,但它并没有真正起作用(那时路由似乎完全中断了).
I also tried to change $stateChangeSuccess
to $stateChangeStart
, but it didn't really work (routing seems to be completely broken then).
推荐答案
如何使用解析块?
.state('app.dashboard', {
url: '/dashboard',
views: {
menuContent: {
templateUrl: 'dashboard/dashboard.html',
controller: 'DashboardCtrl',
resolve: {
login: function($q, Auth) {
var deferred = $q.defer();
Auth.getCurrentUser().then(function(currentUser) {
if (currentUser == null) {
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
}
}
})
在承诺解决之前不会发生状态更改,因此不应显示模板.根据这个答案,拒绝承诺将引发$stateChangeError
,因此您需要处理该问题错误并重定向到登录页面.
The state-change won't happed untill the promise is resolved so the template should not be showing. Rejecting the promise will raise a $stateChangeError
according to this answer so you would need to handle that error and redirect to the login-page.
这篇关于Angular ui-router:如何推迟渲染模板直到授权完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!