I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user information from the token using the following code snippet:
mymodule.run(function ($rootScope, $cookies, AuthService, Restangular) {
if ($cookies.usertoken) {
// call GET api/account/
Restangular.one('account', '').get().then( function(user) {
AuthService.setCurrentUser(user);
});
}
});
The AuthService module looks like this:
mymodule.factory('AuthService', function($http, $rootScope) {
var currentUser = null;
return {
setCurrentUser: function(user) {
currentUser = user;
},
getCurrentUser: function() {
return currentUser;
}
};
});
However, when a controller that requires the user variable is accessed:
mymodule.controller('DashboardCtrl', function (AuthService) {
var user = AuthService.getCurrentUser();
});
The issue arises because the controller code gets executed before the API call completes, resulting in a null value for the user variable. Is there a recommended approach to ensure that the controllers wait for user data to load before initiating?
I came across this link, but I am interested in a more overarching method to initialize the application context.