How can I move HTTP requests from an AngularJS controller and to a service?

I have the following code snippet:

angular.module('test', []).controller('TestCtrl', function ($scope, $http) { $scope.selectedTestAccount = null; $scope.testAccounts = []; $http({ method: 'GET', url: '/Admin/GetTestAccounts', params: { applicationId: 3 } }).success(function (result) { $scope.testAccounts = result; }); } 

I was asked so that I could think of creating a service (s) for $ http requests Can someone give me an example of how I can do this for the code above. In particular, I'm not sure how to configure the service and force the controller to enter it.

+7
source share
1 answer

Your service should look something like this:

 angular.module('testaccount', []). factory('TestAccount', function($http) { var TestAccount = {}; TestAccount.get = function(applicationId, callback) { $http.get('/Admin/GetTestAccounts?applicationId=' + applicationId).success(function(data) { callback(data); }); }; return TestAccount; }); 

Your controller needs to enter the service, call the service object with the parameter and send the callback function:

 angular.module('test', ['testaccount']).controller('TestCtrl', function ($scope, TestAccount) { $scope.selectedTestAccount = null; $scope.testAccounts = []; TestAccount.get(3, function (data) { $scope.testAccounts = data; }) } 

Learn more about dependency injection services in a tutorial.

+14
source

All Articles