title: Loading user context before controllers in AngularJS
body: <p>I developed an <a href="/questions/tagged/angularjs" class="post-tag" title="show questions tagged &#39;angularjs&#39;" rel="tag">angularjs</a> 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:</p>
  
  <pre><code>mymodule.run(function ($rootScope, $cookies, AuthService, Restangular) {
      if ($cookies.usertoken) {
          // call GET api/account/
          Restangular.one('account', '').get().then( function(user) {
              AuthService.setCurrentUser(user);
          });
      }
  });
  </code></pre>
  
  <p>AuthService:</p>
  
  <pre><code>mymodule.factory('AuthService', function($http, $rootScope) {
      var currentUser = null;
  
      return {
          setCurrentUser: function(user) {
              currentUser = user;
          },
          getCurrentUser: function() {
              return currentUser;
          }
      };
  });
  </code></pre>
  
  <p>But if the user accesses a controller which needs a user variable:</p>
  
  <pre><code>mymodule.controller('DashboardCtrl', function (AuthService) {
       var user = AuthService.getCurrentUser();
  });
  </code></pre>
  
  <p>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?</p>
  
  <p>I've found <a href="https://stackoverflow.com/questions/11972026/delaying-angularjs-route-change-until-model-loaded-to-prevent-flicker/11972028#11972028">this link</a> but I'm looking for a more global method to initialize app context.</p>