到目前为止我是这样做的:
angular
.module('mean-starter')
.factory('Auth', function($http, $state, $window, $cookies) {
var currentUser = {};
return {
signup: function(user) {
return $http
.post('/users', user)
.then(function(data, status, headers, config) {
angular.copy(data, currentUser);
$cookies.put('userId', data._id);
$window.location.href = '/';
})
;
},
login: function(user) {
return $http
.post('/login', user)
.then(function(data) {
angular.copy(data, currentUser);
$cookies.put('userId', data._id);
$window.location.href = '/';
})
;
},
logout: function() {
$http
.get('/logout')
.then(function() {
angular.copy({}, currentUser);
$cookies.remove('userId');
$window.location.href = '/';
})
.catch(function() {
console.log('Problem logging out.');
})
;
},
getCurrentUser: function() {
// user is logged in
if (currentUser._id) {
return currentUser;
}
// user is logged in, but page has been refreshed and currentUser is lost
if ($cookies.get('userId')) {
return $http.get('/current-user')
.then(function(data) {
angular.copy(data, currentUser);
})
;
}
// user isn't logged in
else {
return currentUser;
}
},
isLoggedIn: function() {
return !!currentUser._id;
}
};
})
;
重新加载页面后,Auth工厂将重新运行,currentUser
将重新分配给{}
。因此,如果用户已登录,currentUser
将无法反映。所以我必须检查!currentUser._id && $cookies.get('userId')
的情况,如果是,请查询数据库以查找当前登录的用户。
现在我想访问currentUser
:
angular
.module('mean-starter')
.run(run)
;
function run($rootScope, Auth, $state) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (typeof toState.authenticate !== 'undefined') {
var currentUser = Auth.getCurrentUser();
var admin = currentUser.role === 'admin';
var authorized = currentUser._id.toString() === toParams.id;
if (!Auth.isLoggedIn()) {
event.preventDefault();
alert('Must be logged in to access this route.');
$state.go('login');
}
else if (toState.authenticate.authorized) {
if (!admin && !authorized) {
event.preventDefault();
alert('You are not authorized to access that route.');
}
}
else if (toState.authenticate.isAdmin) {
if (!admin) {
event.preventDefault();
alert('You must be an admin to access this route.');
}
}
}
});
}
问题在于我不知道Auth.getCurrentUser()
是否会返回用户或承诺。我该如何检查?该如何构建?
答案 0 :(得分:2)
为什么不总是在$q
的帮助下在getCurrentUser
中回复承诺?
这样的事情
getCurrentUser: function() {
if (currentUser._id || !$cookies.get('userId')) {
// $q.when will wrap your currentUser into a promise
return $q.when(currentUser);
}
return $http.get('/current-user')
.then(function(data) {
angular.copy(data, currentUser);
return currentUser;
});
}
}
并在您的控制器中:
Auth.getCurrentUser().then(function(currentUser) {
// Your code
})
答案 1 :(得分:0)
您可以使用$ q调整函数以在两种情况下返回promise。在这种情况下,所有三个逻辑路径都应该产生相同的结果,尽管它们之间有不同的操作集,因此承诺在这里可以完美地工作。特别是因为您可以非常具体地控制错误处理流程(如果需要)
http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/