I developed an angularjs app and I've a REST API for fetching app resources from my AngularJS app. When the user logs himself, I save his access token in a cookie. If he refreshes the page, I want to get back user information from the token like:
mymodule.run(function ($rootScope, $cookies, AuthService, Restangular) {
if ($cookies.usertoken) {
// call GET api/account/
Restangular.one('account', '').get().then( function(user) {
AuthService.setCurrentUser(user);
});
}
});
AuthService:
mymodule.factory('AuthService', function($http, $rootScope) {
var currentUser = null;
return {
setCurrentUser: function(user) {
currentUser = user;
},
getCurrentUser: function() {
return currentUser;
}
};
});
But if the user accesses a controller which needs a user variable:
mymodule.controller('DashboardCtrl', function (AuthService) {
var user = AuthService.getCurrentUser();
});
the controller code was executed before the end of the API call so I've a null var. Is there a good solution to wait on user data loading before starting controllers?
I've found this link but I'm looking for a more global method to initialize app context.