Ajax calls are an integral part of modern web applications. Angular provides two different APIs to handle Ajax requests, $http and $resource. They are

  1. $http
    It is an AngularJS service for reading data from remote servers. It SIMPLY makes a request to the server, and returns a response.
    $http service methods are listed below:
    • get()
      General syntax:

      Note: Its perfectly fine to use success instead of then if you want the factory to return the original $http promise
    • post()
      General syntax:
    • delete()
      $http.delete(url, [config])
    • head()
    • jsonp()

      Config:method – used to set the HTTP method ( GET, POST, PUT, DELETE, HEAD ).URL – Requesting URL.parameter – It is an optional or we can pass additional parameters to destination.headers – to sent additional HTTP headers to the server.

      timeout – abort the request once the specified waiting time limit is reached.

      cache – enable for XHR request cacheing.

      Promise Object:

      success – If the callback function got succeed, success function will execute.

      error – If the Callback function failed, then it will execute.

    • patch()
    • put()
      <div ng-app=”myApp” ng-controller=”AngularCtrl”>
      <tr ng-repeat=”x in topics”>
      <td>{{ x.Name }}</td>
      <td>{{ x.Description }}</td>
  2. $resource
    Angular’s $resource is a factory which creates a resource object that lets you interact with RESTful backends easily. $resource wraps $http for use in RESTful web API scenarios, as REST is a subset of HTTP. The $resource service doesn’t come bundled with the Angular script. You’ll need to download it (“angular-resource.js“) and include it in your project.Syntax:
    $resource(url, [paramDefaults], [actions], options)
    A resource “class” object with methods for the default set of resource actions optionally extended with custom actions
    a. url
    A parameterized URL template with parameters prefixed by :
    b. paramDefaults (optional)
    Default values for url parameters.
    c. actions(optional)

    d. options
  3. Third-party libraries
    We can also use third-party libraries like Restangular to abstract away pain points of dealing with API responses.

Leave a Reply