user1464139
user1464139

Reputation:

How can I pass back a promise from a service in AngularJS?

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?

Upvotes: 4

Views: 2079

Answers (1)

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

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...  
});

Upvotes: 3

Related Questions