title: Move $http call with $modal to a service in AngularJS
body: <p>I have a bunch of repeating code in one of my modules and I'm very confused on the best way to get this out of all of my controllers.  I have a service that manages a list of user profiles.  These are stored in the sessionStorage locally, but if it's empty the service makes a $http call to the API and then caches the results.  The user could enter one of several different pages, so I need to ensure the data is loaded before displaying the screen.  I use $modal to pop-up a box saying that it's loading the profile while the profile services does it's think.  If it's in sessionStorage, it's a blink; if it has to make the API call, it sits for a few seconds while it does so.</p>
  
  <p>Here is the repeating code in my controllers:</p>
  
  <pre><code>var modal = $modal.open({ templateUrl: 'template/modal/loadingProfile.html' });
    profileService.getUserBySequence($routeParams.sequence).then(function (data) {
      $scope.user = data;
      profileService.getProfileForUser($scope.user.Sequence).then(function (data) {
        var stop = $timeout(function () {
        if (modal.opened) {
          modal.close();
          $timeout.cancel(stop);
        }
      }, 100);
      $scope.profile = data;
    });
  });
  </code></pre>
  
  <p>That's not very pleasant to have at the top of every controller.  Here's a look at the profile service:</p>
  
  <pre><code>function getUserBySequence(sequence) {
      var defer = $q.defer();
      getUserList().then(function (data) {
          defer.resolve(data['_' + sequence]);
      }, function(result) {
          alertService.show(result.data.flash);
          defer.reject();
      });
      return defer.promise;
  }
  
  function getUserProfile(sequence) {
   var defer = $q.defer();
   var profile = sessionService.get('profile.' + sequence, true);
   if (profile) {
      defer.resolve(profile);
   } else {
      var companyId = sessionService.get('companyId');
      $http.get("http://domain.com/api/getProfile?id=" + companyId + "&amp;sequence=" + sequence).then(function (result) {
  
         // only parse if a string
         if (typeof result.data == "string") {
            profile = JSON.parse(result.data);
         } else {
            profile = result.data;
         }
  
         sessionService.set('profile.' + sequence, profile, true);
         defer.resolve(profile);
      }, function (result) {
         sessionService.unset('profile.' + sequence);
         alertService.show(result.data.flash);
         defer.reject();
      });
   }
   return defer.promise;
  }
  </code></pre>
  
  <p>What is the best way to get the controller cleaned up?</p>