我正在使用 this tutorial找出我正在使用的网络应用程序的身份验证系统。如果用户尝试访问需要身份验证的页面之一,我正在使用 ui-router 的 StateProvider 和 resolve 系统将用户重新路由到主页。一切似乎都在工作,除了解决部分似乎实际上没有工作——即我的身份验证返回一个被拒绝的 promise ,但页面加载正常,尽管事实上应该因此而出现某种错误。我做错了什么?
应用程序状态.js
angular
.module('app')
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
// checks if user is logged in or not
// passes back rejected promise if not, resolved promise if true
function authenticated(authFactory, $q) {
var deferred = $q.defer();
authFactory.authenticate()
.then(function(authenticate) {
if (authenticate.data === 'true') {
deferred.resolve();
} else {
deferred.reject();
}
});
return deferred.promise;
}
// every new state that should include a sidebar must have it as a view
$stateProvider
.state('dashboard', {
url: '/dashboard/',
views: {
'sidebar': {
templateUrl: 'app/components/navbar/sidebar.html',
controller: 'SidebarController as vm'
},
'content': {
templateUrl: 'app/components/authenticated/dashboard.html',
controller: 'DashboardController as vm'
}
},
resolve: {
authenticated: authenticated
}
})
应用程序运行.js
function runBlock($rootScope, $log, $state) {
$rootScope.$on('$stateChangeError', function () {
// Redirect user to forbidden page
$state.go('forbidden');
});
}
auth.factory.js
'使用严格';
angular
.module('app')
.factory('authFactory', authFactory);
authFactory.$inject = ['$http', '$cookies'];
function authFactory($http, $cookies) {
var _token;
var service = {
authenticate: authenticate
};
return service;
// used to prevent user from accessing pages that they shouldn't have access to
// this is used exclusively in app.routes.js/app.states.js
function authenticate() {
// gets user's token from cookies, if no cookie, _token will be blank and server will return 403
// this part might be redundant with other functions, but I left it in for now just to make sure
if ($cookies.getObject('user')) {
_token = $cookies.getObject('user').token;
} else {
_token = '';
}
var request = $http({
method: 'POST',
url: 'http://localhost:8080/checkToken',
headers: {'x-auth-token': _token},
transformResponse: function(data) {
return data;
}
});
return request;
}
}
最佳答案
您需要将 return deferred.promise
放在 then 函数之外,这样 promise 才能正确返回。
代码
function authenticated(authFactory, $q, $log) {
var deferred = $q.defer();
authFactory.authenticate()
.then(function(authenticate) {
if (authenticate.data === 'true') {
deferred.resolve();
} else {
deferred.reject();
}
});
return deferred.promise; //placed outside function
}
关于javascript - 状态解析在 ui-router 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661636/