Consuming RESTful APIs with $resource service in AngularJS

Updated on     Kisan Patel

AngularJS $resource service creates a resource object that allows us to intelligently work with RESTful server-side data sources.

The $resource service allows us to turn our $http requests into simple methods like save or update. Rather than requiring us to be repetitive or to write tedious code, we can use the $resource method to handle it for us.

Angular ngResource module needs to be separately loaded since it is not included in the base angular.js file:

<script src="angular-resource.js">

Let us now start by defining the application module and our Student model as an Angular service:

var myModule = angular.module("app", ['ngResource']);

myModule.factory("Student", function($resource) {
     return $resource("/api/student/:id");
});

Here, We define the $resource by passing the URL schema only. This gives us a handful of nice methods including query, get, save, remove and delete to work with our resource.

Now we can use our service to retrieve a list of students inside a controller (example: HTTP GET /api/student):

myModule.controller('studentController', function ($scope, Student) {
   $scope.students = [];

   Student.query(function(data) {
       $scope.students = data;
   });
});

You can also get a specific student by id (example: HTTP GET /api/student/1):

myModule.controller('studentController', function ($scope, Student) {

   Student.get({ id: 1 }, function (data) {
       $scope.student = data;
   });

});

You can also create a new student using save (example: HTTP POST /api/student):

myModule.controller('studentController', function ($scope, Student) {

    var data = { Name: 'Great', RollNo: '47'};
    Student.save(data);

});

You can also delete a specific student by id (example: DELETE /api/student/1):

myModule.controller('studentController', function ($scope, Student) {

    Student.delete({ id: 4 });

});

AngularJS

Leave a Reply