Recently we started using AngularJS for our project and we are using $http for calling Restful API. But, we noticed that every time we have to define a separate function for each $http method, which resulted in larger code base and repetitive task of defining functions. To avoid this situation we explored around possible solutions and found out about $resource service. It helps a lot in managing our code base and also in making our AJAX calls cleaner. Below you can see how to use $resource to make smarter and cleaner RESTful api calls.
WHAT IS $resource ?
Angular provides a very useful optional service (because it doesn’t come with AngularJS) called the $resource service. This service creates a resource object that allows us to smartly work with RESTful server-side data sources.
$resource service wraps $http and exposes handy methods for performing CRUD operations. We can use this methods for calling RESTful api and can save our time.
$http vs $resource
- $http service is used for dealing with RESTful & Non-RESTful It can make AJAX call in both ways.
- $resource service is a wrapper of $http and it is specific for theRESTful part.
- $resource is like, defined once and can be used throughout our controller/service to call get, post, query, remove & delete. The good thing about the $resource is that it has all of the convenience methods built-in.
- By using $resource for calling REST Api we don’t need to write repetitive code and in this way we can make our calls shorter & meaningful.
$resource way to call RESTful api:
This will return a resource object, which contains get(), save(), query(), remove() and delete() methods built-in.
$http way to call RESTful api:
See here we need to define a separate function for each $http method. We have to do repetitive task of defining functions.
PREREQUISITES
For using $resource service we need to download a separate file i.e., angular-resource.js and include in our HTML page. Also, in order to use $resource we need to declare ngResource dependency on our main app module.
USING $resource
The $resource service basically is a factory that creates a resource object.
The returned $resource object has methods that provide a high-level API to interact with back-end servers.
- get() – This method sends a GET request and expects a JSON response.
- query() – This sends a GET request and expects a JSON array response.
- save() – This method sends a POST request and uses the payload to generate the request body.
- delete() – This method sends a DELETE request to the URL and uses the payload to generate the request body.
- remove() – This is similar to delete() method and primarily exists because delete is a reserved word in JavaScript that can cause problems when we use in Internet Explorer.
Let’s see how we can use this methods in a controller: