4

I have some code in my controller that was directly calling $http to get data. Now I would like to move this into a service. Here is what I have so far:

My service:

angular.module('adminApp', [])
.factory('TestAccount', function ($http) {
    var TestAccount = {};
    TestAccount.get = function (applicationId, callback) {
        $http({
            method: 'GET',
            url: '/api/TestAccounts/GetSelect',
            params: { applicationId: applicationId }
        }).success(function (result) {
            callback(result);
        });
    };
    return TestAccount;
});

Inside the controller:

   TestAccount.get(3, function (data) {
      $scope.testAccounts = data;
   })

How can I change this so rather than passing the result of success back it passes back a promise that I can check to see if it succeeded or failed?

1
  • $http itself returns a promise so can use all the methods from $q promise API on it, or use error callback Commented Apr 14, 2013 at 16:57

1 Answer 1

3

Make your service to return a promise and expose it to service clients. Change your service like so:

angular.module('adminApp', [])
.factory('TestAccount', function ($http) {
    var TestAccount = {};
    TestAccount.get = function (applicationId) {
        return $http({
            method: 'GET',
            url: '/api/TestAccounts/GetSelect',
            params: { applicationId: applicationId }
        });
    };
    return TestAccount;
});

so in a controller you can do:

TestAccount.get(3).then(function(result) {
   $scope.testAccounts = result.data;
}, function (result) {
    //error callback here...  
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.