title: AngularJS - Dependency injection involving asynchronous data
body: <p>I want to make the currently logged in user's ID and user name available to my Angular directives. I have created an API end-point to retrieve this information (along with some other information).</p>
  
  <p>The problem is that the API call is asynchronous:</p>
  
  <pre><code>var url = baseUrl + 'api/sessions';
  $http.get(url)
  </code></pre>
  
  <p>I am trying to create a factory that will return the JSON object returned by the API. However, since the call is asynchronous, I don't know how to implement the factory method.</p>
  
  <p>Additionally, I don't want to instantiate the directives until after the value comes back from the API. Is there a mechanism built in to AngularJS that will make sure the asynchronous call has returned first, or should I just create a global object and update its values when the call returns (using the JSON object)?</p>
  
  <p>This is what I currently have:</p>
  
  <pre><code>application.factory('session', ['$http', 'baseUrl', function ($http, baseUrl) {
      var session = {};
      var url = baseUrl + 'api/sessions';
      var promise = $http.get(url)
          .success(function (data) {
              for (var key in data) {
                  session[key] = data[key];
              }
          });
      return session;
  }]);
  </code></pre>
  
  <p>The problem is that any dependent directives are retrieving the session object before it is populated. I am concerned that if the API call takes a long time, the session object will be uninitialized when the user goes to use it.</p>