I am faced with the challenge of redirecting a user who is not logged in back to the login page, but I am uncertain about how to implement this particular functionality.
My current setup includes:
- MainController: connected to the body tag and accessible throughout the entire application
- AccountController: linked through routing to account.html
- LoginController: linked through routing to login.html
- UserService: contains the user object fetched from the server and a refresh() method for updating it
The MainController triggers the refresh() method of the UserService upon startup and every 10 seconds. Now, my aim is to direct a user attempting to access account.html to login.html if they are not logged in. To achieve this, I need to check the user variable within my UserService from the AccountController:
var init = function() {
if(UserService.user == null) {
//redirect
}
};
init();
The issue lies in the fact that the user variable is initially empty as data retrieval by the MainController from the server is asynchronous.
What would be the optimal approach to tackle this problem? One solution could involve using events to inform the AccountController when the data becomes available. Alternatively, I could implement a while loop in the AccountController to wait until the data is populated.
//EDIT: Another option could be calling the refresh() method within the init() function of each controller I have (employing deferred to verify the user variable afterwards), but this would lead to code duplication across multiple controllers.