Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


You might be a bit surprised to see method and url among configuration options since
those parameters can be already supplied as part of a $http methods' signatures. It
turns out that $http itself is a function that can be invoked in a generic way:


$http(configObject);

The generic form might be useful for cases where AngularJS doesn't provide a
"shortcut" method (for example for PATCH or OPTIONS requests). In general we
find that shortcut methods result in a more concise and easier way to read code, and
we would recommend using this form over the generic one whenever possible.


Request data conversion

The $http.post and $http.put methods accept any JavaScript object (or a string)
value as their data parameter. If data is a JavaScript object it will be, by default,
converted to a JSON string.


The default data to JSON conversion mechanism ignores all properties
starting with a dollar sign ($). In general, properties beginning with $ are
considered "private" in AngularJS. This might be problematic for some
back-ends to which we need to send properties with the $ (for example,
MongoDB). The workaround is to convert data manually (using the
JSON.stringify method, for example).

We can see the data conversion in action by issuing a POST request to create a new
user in MongoLab:


var userToAdd = {
name:'AngularJS Superhero',
email:'[email protected]'
};

$http.post('https://api.mongolab.com/api/1/databases/ascrum/collec
tions/users',
userToAdd, {
params:{
apiKey:'4fb51e55e4b02e56a67b0b66'
}
});

This example also illustrates how HTTP query string parameters (here: apiKey) can
be added to a URL.

Free download pdf