Here's one way I like to handle this, assuming that Restangular returns the new promise from then
(I haven't used Restangular). The promise can be stored somewhere like on AuthService
and then used later in the controller. First, add a property to AuthService
to hold the new promise:
return {
authPromise: {}, // this will hold the promise from Restangular
// setCurrentUser, getCurrentUser
// ...
When calling Restangular, save the promise and be sure to return the user data so that the controller can access it later, like this:
AuthService.authPromise = Restangular.one('account', '').get()
.then( function(user) {
AuthService.setCurrentUser(user);
return user; // <--important
});
Lastly, create a new promise in the controller that will set the user
variable.:
mymodule.controller('DashboardCtrl', function (AuthService) {
var user;
AuthService.authPromise.then(function(resultUser){
user = resultUser;
alert(user);
// do something with user
});
});
Demo: Here is a fiddle where I've simulated an AJAX call with $timeout
. When the timeout concludes, the promise resolves.