Angular.js

Angular.js Http Post Example

Angular.js is famous for it’s Rest APIs and the simple ways it offers for us to communicate with remote HTTP servers. All this is done through the $http service via the browser’s XMLHttpRequest or JSON with Padding (alias JSONP). Let’s give a go at learning how to do that in real life examples, shall we?

1. The $http service

The AngularJS $http service is a function that makes a call to a remote HTTP server and returns a response. This service takes a single object as it’s argument: the configuration object. But what exactly is a configuration object?

1.1 The configuration object

It’s an object describing in detail the request that is to be made and how it should be processed by the receiver. It comes with a set of properties that ensure exactly that, too. Some of these are:

  • method – a string that describes the HTTP method to be used, which can either be GET, POST, DELETE, etc.
  • url – a string which represents the absolute or relative URL to the resource you’re requesting from.
  • params – a map of objects that will be serialized and appended as GET parameters.
  • data – is either a string or object of data to be sent as request message data.
  • eventHandlers – event listeners that are to be bound to the XMLHttpRequest.
  • timeout – is the timeout in milliseconds, or promise that should abort the request when resolved.

These are the most important ones, but note that there are a number of other properties related to it, which you can very easily look up when you need them. The configuration object returns a promise that will be resolved to a response object when the request succeeds or fails.

1.2 The syntax

This may seem a bit hazy for now, but let’s explain the general way to generate an HTTP request using $http, and it’ll be much clearer. Take a look at the syntax below:

syntax.js

$http({
  method: 'POST',
  url: '/yourURL'
}).then(function successCallback(response) {
                //code for what happens when the request is successful
  }, function errorCallback(response) {
                //code for what happens when there's an error
  });

What we’ve done here is pretty simple. You specify the method and url of the $http request, and then use the then() function to invoke two actions: either the first callback named successCallback() which will be run asynchronously when the response is available, as it takes one as an argument, or the second callback errorCallback(response) which is invoked asynchronously in case the server returns an error status, or one occurs along the way.

1.3 The response object

The response object, being exactly that, enjoys some perks of it’s own. It has a number of properties which can be thought as components of the object. These would be:

  • data – is a string containing the response body transformed using the transformation functions
  • status – a number which serves as a code representing the status of the response
  • headers – is the header getter function
  • config – the configuration object that was used to generate the request
  • statusText – HTTP status text of the response

The status can be any number, but only 200-299 will be considered success statuses and the rest will be taken for errors and will trigger the errorCallback. In case the status is a negative number it will be normalized to 0. Usually -1 is used to show that the request was aborted, and if the response is a redirect the status will be the final response status code.

2. Shortcut Methods of $http

AngularJS provides us with a number of shortcut methods for the basic usage of the $http service. These shortcut methods would be:

  1. $http.get – generates Http GET request and retrieves server data if the request is successful.
  2. $http.post – generates Http POST request and retrieves server data if the request is successful.
  3. $http.put – generates Http PUT request and retrieves server data if the request is successful.
  4. $http.delete – generates Http DELETE request and retrieves server data if the request is successful.
  5. $http.head – generates Http HEAD request and retrieves server data if the request is successful.
  6. $http.patch – generates Http PATCH request and retrieves server data if the request is successful.
  7. $http.jsonp – generates Http JSONP request and retrieves server data if the request is successful.

All of these methods send a request to the HTTP remote server and get data from them in response. We’ll explain each of them shortly and then focus on $http.post. After we finish with all the details of that one, you’ll know the drill about basically each of them.

There are two (very similar, if I might add) scenarios of how the syntax of these methods could go. The first one is valid for all the methods above except $http.post and $http.put. It would go like below:

syntax.js

$http.get('/yourURL', config).then(successCallback, errorCallback);

We’ve used $http.get as an example, but it’s the same for all of them. The method only takes one mandatory parameter as an argument, and that would be the URL of the resource to which you’re sending the request. In our case, that is /yourURL.

However, you can also add a second argument which you’re not obligated to, which is the configuration object, used to describe the request and how it is to be handled in detail. After that you only have to invoke the callbacks in case of success or failure, which we’ve aptly named successCallback and errorCallback. To do that, we’ve used the then() function, assuming that you’re using a version of Angular that is released later than v1.4.8 (or usually considered v1.5.0).

Let’s see now the syntax for the two remaining methods: $http.post and $http.put. The code would go like below:

syntax.js

$http.put('/yourURL', data, config).then(successCallback, errorCallback);

As you can see for yourself, there is basically no other difference except one added argument to the method. That would be data and it’s an argument you’re obliged to pass on. Like we mentioned, it’s an object which would contain the response body transformed using the transform functions.

3. The $http.post shortcut

We saw how to use each shortcut of the $http service in general, but let’s focus on just one of them and take it apart. We’ll focus on $http.post for this example, but as previously made clear, you can use this as a guide for all the other methods as well.

3.1 Syntax

While you’re already familiar with the syntax in case your AngularJs is v1.4.8+, you might want to know how to use this feature in case you decide that your version of choice is of an earlier date than that. The syntax would look like that in the code snippet below:

syntax.js

   $http.post('/yourURL', data, config)
              .success(function (data, status, headers, config) {
              })
              .error(function (data, status, header, config) {
              });            

You’re already familiar with the greater part of this code snippet, and while you might already have guessed what the other parts do, we want to make it clearer for everyone. You see that we have used two methods there, which are success() and error(). These methods are called $http legacy promise methods, and yes, they were used to invoke the successCallbacks and errorCallbacks.

However, they have been deprecated since the release of Angular.js v1.4.8, and instead of those, we use the standard then() method. If you insist on using them you have to make sure that $httpProvider.useLegacyPromiseExtensions is set to TRUE, because if not, you’ll have an error thrown.

3.2 Legacy Promise Methods vs. then()

As Legacy Promise Methods we named two of them: success() and error(). While these have been arguably useful as $http promise methods, they’re not standard, meaning only $http promises have had them, while all other regular promises used then(). Which brings us to the first reason for these methods being deprecated: inconsistency. It isn’t very nice when you have to switch from one way to another. If I can just keep using one method while choosing from a number of them, then I’ll use the one which is all encompassing and is valid for the bigger picture, right? It’s only a matter of habit.

….not that much. While consistency is a big part of it, there are other reasons, which I’d call more important, for why we only use then() in the newer versions of Angular. So, by now we know that one of the major benefits of promises is the ability to flatten and chain code. While success() and error() might be visually appealing and fairly convenient for simple calls with no chaining, when chaining them we’re in for a little bit of a treat.

While then() would give us an new promise each time it’s fired, success() and error() would give us the original promise and not a derived one, which is the whole point of chaining to begin with. That happens not because these two methods do not allow chaining, as they formally do. The reason is because when using success(), all the handlers will be fired during the same cycle, and the second handler will be fired before the newly returned promise is resolved. That would give us errors, and it’s only reasonable that the methods are deprecated.

4. Simple $http.post example

What we will do here is introduce you to a simple example of the usage of $http.post. The idea on the user’s point of view is to submit a string (which can be a name, number, or whatever you wish) through an input field and then have that information displayed. For that we only have to use the $http.post shorcut method and a function that makes the JSON data into a string. The code for the HTML part would go like below:

post.html

<body ng-app='myApp'>

<div ng-controller="myCtrl">

    <form ng-submit="sendPost()">
        <input ng-model="newName"/>
        <button type="submit">Send</button>
</form>

{{hello.name}}

</div>

</body>

As you see, we’ve used standard AngularJS syntax such as the one for the ng-app or ng-controller. We’ve bound the information entered in the input field to the ng-model and then we have used the expression to display it. Let’s take a look at all the behind the scenes of this part:

post.js

angular.module('myApp', [])
.controller('myCtrl', function ($scope, $http) {
    $scope.hello = {name: "ERA"};
    $scope.newName = "";
    $scope.sendPost = function() {
        var data = $.param({
            json: JSON.stringify({
                name: $scope.newName
            })
        });
        $http.post("/echo/json/", data).success(function(data, status) {
            $scope.hello = data;
        })
    }
})

First, before any name is entered in the input field, you’ll have the default ERA displayed, which we have saved at the $scope.hello variable. The initial information in the input field is just an empty string, and we’ve saved it into the $scope.newName, as you might have noticed in the HTML part of the code.

You might have also noticed that the ng-submit would invoke a function named sendPost() which is the one that “stringifies” the data entered in the input field and posts it using $http.post by replacing $scope.hello with that info.

What is worth noting in this code snippet is the syntax used for the $http.post shortcut, which is the one used with the earlier versions of Angular JS. Remember to use the standard method then() instead of success() if you’re using the latest versions.

Don’t forget to include any external parts necessary into your main document such as the AngularJS file (I did forget that once while learning Angular. Don’t laugh!) or jQuery. With that, you’re set to go!

5. Download the source code

This was an example of $http.post using AngularJS.

Download
You can download the full source code of this example here: $http.post

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button