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

I have code in my controller that directly called $ http to receive data. Now I would like to move this to a service. Here is what I still have:

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, instead of passing the result of success back, it returns a promise that I can check to make sure that it succeeded or failed?

+4
source share
1 answer

Make your service to return a promise and expose it for customer service. Change your service like this:

 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 the controller you can:

 TestAccount.get(3).then(function(result) { $scope.testAccounts = result.data; }, function (result) { //error callback here... }); 
+3
source

All Articles