Currently have a small application with a
- login view
'/login'
- homepage view
'/home'
- logged-in-homepage view
'/dashboard'
when the user navigates to the homepage after being loggedin i wanted to show him the logged-in-homepage. I tried giving a redirectUrl
to the $routeProvider
. If i return an empty string there it stays on the page, and if it returns a string like '/dashboard'
then it redirects to the dashboard.
the problem is i cannot check whether the user is logged in, in that function in the config. because I cannot inject my UserService
in there.
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'
}
)
});
the UserService which holds user state:
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
};
}
]
);
is there a way to get to the user state from the config? without it being public (I don't want to make the user accessible on the window object for example...)
or should i get that info from a cookie, or other system?