CRUD operations using $resource

In order to expose a RESTful web API, we can use the $http service, as shown in the previous CRUD operation using $http section. As we can see, in order to use $http, we created the methods Create, Read, and so on. However, on the other hand, we can use $resource, which provides a higher level of abstraction built on top of $http. The ngResource module is not included in the AngularJS framework:

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

First, in our controller, we create a function named customerResources:

<!-- RETREIVE DATA FROM DATABASE WITH $resource & WEB API -- >
   
app.controller('ctrlCustomer', function ($scope, $http) {

 var customerResource = $resource('/api/Customer/Customer', {}, {

        'get': { method: 'GET' },
        'query': { method: 'GET', isArray: true },
        'save': { method: 'POST' },
        'delete': { method: 'DELETE' },
        'add': { method: 'POST' },
        'update': { method: 'PUT' }

    });

});

Then, we use the customerResource function to implement the HTTP verbs GET, POST, PUT, DELETE, and so on. This code shows the use of customResource, which we created earlier:

app.controller('ctrlCustomer', function ($scope, $http) {

var customerResource = $resource('/api/Customer/Customer', {}, {

        'get': { method: 'GET' },
        'query': { method: 'GET', isArray: true },
        'save': { method: 'POST' },
        'delete': { method: 'DELETE' },
        'add': { method: 'POST' },
        'update': { method: 'PUT' }

    });

<! --------------  GET ALL CUSTOMERS --------------->
    customerResource.query().$promise.then(function (custList) {

       $scope.Customers = custList;

    }, function (errorResponse) {

        alert('Error'),
    });

    <!----GET SPECIFIC CUSTOMER - BY CUSTOMER ID -------->
    $scope.GetCustomerByCustomerID = function (CustomerID) {

   customerResource.get({ customerID: CustomerID
   }).$promise.then(function (cust) {
            
            $scope.Customer = cust;

        }, function (errResponse) {
            alert('Error'),

        });

    }


    <! --------------- Add New Customer ------------- >    
    $scope.AddCustomer = function (Customer) {

     customerResource.add(Customer).$promise.then(function () {

     <! -- GET THE UPDATED CUSTOMER LIST -- >
     customerResource.query().$promise.then(function (custList) {

                $scope.Customers = custList;

            }, function (errorResponse) {

                alert('Error'),
            });


        }, function (errorResponse) {

            alert('Error'),

        });
    }

    <! --------------- Delete Customer ------------- >
    $scope.DeleteCustomer = function (CustomerID) {
        
    customerResource.delete({ customerID: CustomerID    
    }).$promise.then(function () {


    <! -- GET THE UPDATED CUSTOMER LIST -- >
    customerResource.query().$promise.then(function (custList) {

                $scope.Customers = custList;

            }, function (errorResponse) {

                //FAIL

                alert('Error'),
            });


        }, function (errorResponse) {

            alert('Error'),

        });
    }

});

The advantage of using the AngularJS $resource provider is that it provides a handful of methods, such as query, get, save, remove, and delete to work with resources, as you can see in the preceding code. The returned object of $resource has the basic $save, $remove, and $delete methods. These methods allow us to fetch data and update it, as shown here:

<!----GET SPECIFIC CUSTOMER & UPDATE THE VALUE -------->
    $scope.GetCustomerByCustomerID = function (CustomerID) {

   customerResource.get({ customerID: CustomerID
   }).$promise.then(function (cust) {
            
            cust.CompanyName = "New Company Name" ;
            cust.$save();   

        }, function (errResponse) {
            alert('Error'),

        });

    }

As you have seen in the preceding code, we used $promise. In the AngularJS framework, $promise can be used to allow us to chain multiple functions together, which increases the readability and makes the function more reusable. The $promise can be chained with the following methods:

  • then (successCallback, errorCallback, and notifyCallback): This calls the success or error method asynchronously as soon as the result is available
  • catch: This is a shorthand of then (null and errorCallback)
  • finally (callback and notifyCallback): This allows us to observe fulfilment or failure of a promise
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset