Chances are if you write an Angular app then at some point you’re going to need to communicate with a RESTful web service. On a basic level you could use Angular’s built-in
$http service to do this. There’s nothing wrong with that but there’s more manual work involved with it. Thankfully Angular also provides their
ngResource module that helps reduce verbosity and makes this interaction a little cleaner.
The third option and the one I personally prefer is
Restangular in my opinion provides more features than
ngResource and an even cleaner means of working with resources. Nonetheless, I’m going to demonstrate how to consume a basic RESTful resource using all three methods.
For these examples we’re going to be consuming a RESTful resource that is setup to the following specification.
GET /hammersReturns a collection of hammers
GET /hammers/:idReturns a specific hammer
POST /hammersCreates a new hammer
PUT /hammersUpdates a specific hammer
DELETE /hammers/:idDeletes a specific hammer
$http is fundamentally simple but as you can it requires you to pass a URL every time you make a request. Read more about the
$http service here.
ngResource, once you’ve retrieved objects they are wrapped with instance functions like
$remove which make it easy to perform subsequent operations on them without the need to keep passing a URL.
One downside to using
ngResource is that don’t naturally return promises, which is why you have to chain the
$promise object. Read more about
Restangular follows a similar pattern as
ngResource in that once objects are retrieved they are wrapped with instance functions. One of
Restangular‘s strong points is that you never need to pass it an actual URL, you just specify the starting resource and from there you can scope it down to all, one, or even sub-resources.
Read more about