Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for making an AJAX call in Angular.js?

Tags:

angularjs

People also ask

Which service in angular helps to make Ajax calls?

Inside the ButtonClick function, the $http service is used to make an AJAX call to the ASP.Net WebMethod. The $http service has following properties and methods.

Do we need Ajax in angular?

Angular uses AJAX technology to build single-page applications. Angular offers much more functionality than AJAX, and AJAX vs Angular is an important part of this functionality.


EDIT: This answer was primarily focus on version 1.0.X. To prevent confusion it's being changed to reflect the best answer for ALL current versions of Angular as of today, 2013-12-05.

The idea is to create a service that returns a promise to the returned data, then call that in your controller and handle the promise there to populate your $scope property.

The Service

module.factory('myService', function($http) {
   return {
        getFoos: function() {
             //return the promise directly.
             return $http.get('/foos')
                       .then(function(result) {
                            //resolve the promise as the data
                            return result.data;
                        });
        }
   }
});

The Controller:

Handle the promise's then() method and get the data out of it. Set the $scope property, and do whatever else you might need to do.

module.controller('MyCtrl', function($scope, myService) {
    myService.getFoos().then(function(foos) {
        $scope.foos = foos;
    });
});

In-View Promise Resolution (1.0.X only):

In Angular 1.0.X, the target of the original answer here, promises will get special treatment by the View. When they resolve, their resolved value will be bound to the view. This has been deprecated in 1.2.X

module.controller('MyCtrl', function($scope, myService) {
    // now you can just call it and stick it in a $scope property.
    // it will update the view when it resolves.
    $scope.foos = myService.getFoos();
});

The best practise would be to abstract the $http call out into a 'service' that provides data to your controller:

module.factory('WidgetData', function($http){
    return {
        get : function(params){
            return $http.get('url/to/widget/data', {
                params : params
            });
        }
    }
});

module.controller('WidgetController', function(WidgetData){
    WidgetData.get({
        id : '0'
    }).then(function(response){
        //Do what you will with the data.
    })
});

Abstracting the $http call like this will allow you to reuse this code across multiple controllers. This becomes necessary when the code that interacts with this data becomes more complex, perhaps you wish to process the data before using it in your controller, and cache the result of that process so you won't have to spend time re-processing it.

You should think of the 'service' as a representation (or Model) of data your application can use.


The accepted answer was giving me the $http is not defined error so I had to do this:

var policyService = angular.module("PolicyService", []);
policyService.service('PolicyService', ['$http', function ($http) {
    return {
        foo: "bar",
        bar: function (params) {
            return $http.get('../Home/Policy_Read', {
                params: params
            });
        }
    };
}]);

The main difference being this line:

policyService.service('PolicyService', ['$http', function ($http) {

I put an answer for someone who wanted a totally generic web service in Angular. I'd recommend just plugging it in and it will take care of all your web service calls without needing to code them all yourself. The answer is here:

https://stackoverflow.com/a/38958644/5349719