title: Angular .run() initialising controller values
body: <p>This is my first AngularJS build and I'm totally new to it (I'm primarily a back-end dev).</p>
  
  <p>I need to store some global values, which will then be used by other controllers/directives on the page and will also be passed into API calls to the backend. I'm trying to avoid using the $rootScope and think I can manage this by creating a service to store global/session type values.</p>
  
  <p>I want to be able to load these 'session' values before any other controllers are run.</p>
  
  <p>Everything seems to be working ok - my backend api is being hit and returning a JSON object but I think the homeCtrl is firing too soon, as I am getting a 'Cannot read property of 'user' undefined'.  If I console.log(response.data) then I can see the JSON object so I know it's being returned but this occurs AFTER the user undefined error. </p>
  
  <p>So I think have something wrong with regard to timings and promises.</p>
  
  <p>How should I go about creating a service that I can populate properties on initialise and then share between controllers/directives?</p>
  
  <p>Any pointers or help appreciated </p>
  
  <p>My app JS</p>
  
  <pre><code>var app = angular.module('myApp', ['ngRoute'])
  /* Set our routing and templates */
  .config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  
      /*Enable HTML5 mode - removes # from URL*/
      $locationProvider.html5Mode(true);
  
      $routeProvider
          .when('/', {
              controller: 'homeCtrl',
              template: '&lt;h2 ng-controller="homeCtrl"&gt;We are home&lt;/h2&gt;&lt;p&gt;User type string: {{ userType }}&lt;/p&gt;'
          })
          .when('/my-status', {
              template: '&lt;h2&gt;We are my profile&lt;/h2&gt;'
          })
          .otherwise({redirectTo: '/'});
  }])
  
  /* gather Global variables and store */
  .run(['mySession',function(mySession){
      mySession.init();
  }]);
  
  
  app.controller('homeCtrl', ['mySession', function ($scope, mySession) {
  
  $scope.userType = (mySession.employeeType == "1") ? "Admin" : "User";
  
  }]);
  
  app.factory('mySession',['$http','$q',function($http, $q){
  
      var user = {};
      var displayState = 0;
  
  
      return {
          init : function(){
             return $http.get('/api/users/1')
                  .then(function(response) {
                      if (typeof response.data === 'object') {
                          this.user = response.data;
                          return true;
                      } else {
                          // invalid response
                          return $q.reject(response.data);
                      }
  
                  }, function(response) {
                      // something went wrong
                      return $q.reject(response.data);
                  });
          }
      };
  }]) 
  </code></pre>