This example demonstrates the code that is used to get or retrieve the data from server using AngularJS $http service based on AJAX GET protocol. It also demonstrates the capability of AngularJS dependency injection which is used to inject $http service to the controller as it is initiated.
The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. The detailed article on $http service could be found on AngularJS $http page.
Following data is retrieved from server. The related code is given later below.
Name | Address | City | Phone |
---|---|---|---|
{{profile.firstname + " " + profile.lastname}} | {{profile.address}} | {{profile.city}} | {{profile.phone}} |
{{profiles|json}}
var helloApp = angular.module("helloApp", []);
helloApp.controller("HttpController", [ '$scope', '$http',
function($scope, $http) {
$http({
method : 'GET',
url : '/getAllProfiles'
}).success(function(data, status, headers, config) {
$scope.profiles = data;
}).error(function(data, status, headers, config) {
alert( "failure");
});
} ])
Pay attention to getAllProfiles method which is called from $http service using GET
@RequestMapping(value = "/angularjs-http-service-ajax-get-code-example", method = RequestMethod.GET)
public ModelAndView httpServiceGetExample( ModelMap model ) {
return new ModelAndView("httpservice_get");
}
@RequestMapping(value = "/getAllProfiles", method = RequestMethod.GET)
public @ResponseBody String getAllProfiles( ModelMap model ) {
String jsonData = "[{\"firstname\":\"ajitesh\",\"lastname\":\"kumar\",\"address\":\"211/20-B,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-888-6666\"},{\"firstname\":\"nidhi\",\"lastname\":\"rai\",\"address\":\"201,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-876-5432\"}]";
return jsonData;
}