我想使用ui-router
resolve属性在进入该状态之前简单地检查用户是否使用AuthService
函数登录,但是没有结果。
angular.module('app').config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider, USER_ROLES) {
$stateProvider
.state('dashboard', {
url: "/dashboard",
templateUrl: "app/views/dashboard_2.html",
data: { requiresAuth: true, pageTitle: 'Dashboard', authorizedRoles: ['admin'] } ,
resolve: {
isLoggedin: ['AuthService', function(AuthService) {
return AuthService.isAuthenticated();
}]
}
})
});
'use strict';
angular
.module('app')
.factory('AuthService', function($log, $http, $q, $cookies){
var authService = {};
// .. login and logout methods...
authService.isAuthenticated = function () {
return !!$cookies.getObject('currentUser');
};
return authService;
});
angular
.module('app')
.run(function($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
$rootScope.$on('$stateChangeStart', function (event, to, toParams, from, fromParams) {
// $log.debug('state change starts');
$log.debug(to.resolve);
});
我读到了解析返回promise对象,但我有简单的函数whcih返回true / false
那是问题吗?请建议我以适当的方式做什么,以便答案 0 :(得分:1)
由于resolve
函数需要一个promise,你应该返回一个promise。修改您的代码,如:
isLoggedin: ['AuthService', '$q', function(AuthService, $q) {
var defer = $q.defer();
var isLoggedIn = AuthService.isAuthenticated();
if (isLoggedIn) {
defer.resolve();
} else {
defer.reject();
}
return defer.promise;
}]
或者,您可以从状态配置中删除resolve
关键字并修改run
块,如下所示:
angular
.module('app')
.run(function ($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, from, fromParams) {
if (toState.name === 'dashboard') {
if (!AuthService.isAuthenticated()) {
// Do not allow navigation to state
e.preventDefault();
// Redirect to somewhere else like login page
//$state.go('login')
return;
}
}
});
});
修改强>
你可以修改上面的(第二种方法)代码,使它像这样通用:
angular
.module('app')
.run(function ($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, from, fromParams) {
if (toState.requireAuthenticationFoo && !AuthService.isAuthenticated()) {
// Do not allow navigation to state
e.preventDefault();
// Redirect to somewhere else like login page
//$state.go('login')
return;
}
});
});
现在在状态配置中使用密钥requireAuthenticationFoo
:
state('dashboard', {
url: "/dashboard",
templateUrl: "app/views/dashboard_2.html",
data: {requiresAuth: true, pageTitle: 'Dashboard', authorizedRoles: ['admin']},
requireAuthenticationFoo: true
})