目前有一个小应用程序
- 登录视图
'/login'
- 主页视图
'/home'
- 登录主页视图
'/dashboard'
当用户登录后导航到主页时,我想向他显示登录的主页。我试着给redirectUrl
. $routeProvider
如果我返回一个空字符串,它会留在页面上,如果它返回一个字符串,'/dashboard'
那么它会重定向到仪表板。
问题是我无法在配置中的该功能中检查用户是否已登录。因为我不能UserService
在那里注射我的。
main.js
var myApp = angular.module('myApp', ['ngRoute', 'ngAnimate']);
myApp.config(['$routeProvider', '$locationProvider', function AppConfig($routeProvider, $locationProvider) {
$routeProvider.when(
// entry point, the main route of the app
'/', {
redirectTo: '/home'
}
)
.when(
// home page, entrypoint when a user is not logged in.
'/home', {
redirectTo: function redirectHome() {
// need to get the loggedInState here... preferably not on the window :p
return (window.isLoggedIn) ? "/dashboard" : "";
},
action: 'splash.home'
}
)
.when(
// specific route to the login popup on the homepage
'/login', {
action: 'splash.home.login'
}
)
.when(
// dashboard after being logged in
'/dashboard', {
action: 'base.dashboard'
}
)
});
持有用户状态的 UserService:
myApp.service('UserService',
[
'$http',
function UserService($http) {
// --- Service Variables. ------------------- //
// url to the service that returns the logged in user details
var userServiceUrl = '/user/data/me';
// Store the current user.
var User = {
isLogged: false,
apps: [],
data: {}
};
// --- Service Methods. ------------------- //
// Return whether the user is logged in
function isLoggedIn() {
return User.isLogged;
}
// Return the current user
function getUser(fn) {
fn = fn || function callback() {};
if (!User.isLogged) {
return fetchUser(fn);
} else {
return fn(User);
}
}
// set the current user
function setUser(user, loggedIn) {
loggedIn = loggedIn || false;
User.isLogged = loggedIn;
User.data = user;
}
// get the user from the server
function fetchUser(fn) {
$http.get(userServiceUrl).success(function onGetUserSuccess(data, status, headers, config) {
if (data.success) {
setUser(data.data, data.success);
}
if (fn !== undefined) {
fn(User);
}
})
.error(function onGetUserError(data, status, headers, config) {
setUser({}, false);
});
}
// --- Return Public API. ------------------- //
return {
isLoggedIn: isLoggedIn,
getUser: getUser,
setUser: setUser
};
}
]
);
有没有办法从配置中获取用户状态?没有公开(例如,我不想让用户在窗口对象上访问......)
还是我应该从 cookie 或其他系统中获取该信息?