我正在尝试将登录用户从登录页面重定向到远离登录页面(如果他们尝试在应用程序中访问它)。与登录页面关联的控制器 - Login_controller
调用授权服务中的功能 - Authorisation_service.isLoggedIn()
。如果此服务返回true,则应将用户重定向到登录的概述页面。AngularJS - 控制器不等待条件语句中的服务返回值
通过记录到控制台我可以看到,在服务返回true之前,条件语句已经声明从服务返回的值是未定义的。之后服务确实会恢复正常,但已为时过晚。
如何让控制器的条件语句等待服务的返回值?
Authorise_service.js
myApp.factory('Authorise', ['User', '$http', '$location', '$rootScope', function(User, $http, $location, $rootScope) {
return {
isLoggedIn: function() {
if(((sessionStorage.username && sessionStorage.authKey) && (sessionStorage.username !== "null" && sessionStorage.authKey !== "null")) || ((localStorage.username && localStorage.authKey) && (localStorage.username !== "null" && localStorage.authKey !== "null"))) {
if(sessionStorage.username) {
var usernameLocal = sessionStorage.username;
var authKeyLocal = sessionStorage.authKey;
} else {
var usernameLocal = localStorage.username;
var authKeyLocal = localStorage.authKey;
}
//pass to server
var user = User.query({ usernameLocal: usernameLocal, authKeyLocal: authKeyLocal }, function(user) {
if(user.loginSuccess === 1) {
return true;
} else {
return false;
}
});
} else {
return false;
}
}
};
}]);
Login_controller.js
myApp.controller('Login_controller', function(Authorise, $scope, $location) {
if(Authorise.isLoggedIn() === true) {
console.log("Authorise.isLoggedIn() = true");
$location.path('/teach/overview');
}
});
感谢您的详尽回复和教程链接非常有用 – Fisu 2013-03-08 13:09:31
很高兴能帮助您,先生! – 2013-03-10 15:13:37