Skip to content
AngularJS

$http Service

Promise-based HTTP requests with config object and error handling.

By EZ4Code Team
angularjshttpajax

Code

angular.module('httpApp', [])
.controller('HttpController', function($scope, $http) {
  $scope.users = [];
  $scope.loading = false;
  $scope.error = null;

  $scope.loadUsers = function() {
    $scope.loading = true;
    $http.get('/api/users')
      .then(function(response) {
        $scope.users = response.data;
      })
      .catch(function(error) {
        $scope.error = 'Failed to load: ' + error.status;
      })
      .finally(function() {
        $scope.loading = false;
      });
  };

  $scope.addUser = function(user) {
    $http.post('/api/users', user)
      .then(function(res) { $scope.users.push(res.data); });
  };

  // Config object form with params and headers
  $http({
    method: 'GET',
    url: '/api/users',
    params: { page: 1, limit: 20 },
    headers: { 'Authorization': 'Bearer token' }
  });
});

Explanation

$http returns a promise resolving to a response object with data, status, headers, and config. Convenience methods (get, post, put, delete) cover common verbs, while the config-object form exposes params, headers, and body. AngularJS auto-applies digest-cycle updates after promise resolution, so scope changes render automatically.

More AngularJS Snippets