Angular’s $resource for CRUD Operations

30 / May / 2015 by Rubi Saini 3 comments

$resouce is a perfect option to create a single page application which involve CRUD operations.You don’t write your CRUD methods (create,read,update and delete) when you use it.

A RESTful web service with one endpoint for a data type that does different things with that data type based on HTTP methods like GET, POST, PUT, DELETE, etc. So with a $resource service, you can call a GET method to get the resource as a JavaScript object, then alter it and send it back using POST method, or may perform even delete operation with DELETE method.
As we already said that $resource is use full for REStful service so it expects a classic RESTful back-end and your end point should be in the following format:

Method API URL PAYLOAD Result
GET empty Returns all products
POST JSON Object New product created
GET empty Returns single product
PUT JSON Object Returns all products
DELETE empty Delete existing product

Let’s use it

You need to download a file called angular-resource.js and include it in your HTML page

[js]
<script src= <strong>angular-resource.js</script>
[/js]

Then add as module dependency:

[js]
angular.module("myApp", ["ngResource"]) //myApp is our main
[/js]

After this create a service in you app with $resouce dependency.

Syntax

[js]
$resource(url,{paramDefaults},{actions},{options});
[/js]

Where url is required parameter which is web app url for endpoints.paramDefaults are defaults for url params. The action methods which map to CRUD operations (Note: you can have your own action methods).options are Used to remove the trailing slashes from the url with the help of stripTrailingSlashes property.

Object of $resource returned following action methods to perform CRUD operations

save‘: {method:’POST’},
get‘: {method:’GET’},
query‘: {method:’GET’, isArray:true},
delete‘: {method:’DELETE’} };
remove‘: {method:’DELETE’},

after this , you can use them in your controller to perform CRUD operations:

Example –

Service :

[js]
angular.module(‘myApp’)
.factory(‘ProductService’, [‘$resource’,
function ($resource) {
return $resource(‘/products’, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST"},
get: { method: "GET"},
remove: { method: "DELETE"},
update: { method: "PUT"}
});

}]);
[/js]

Controller:

[js]
angular.module(‘myApp’)
.controller(‘ProductCtrl’, [ ‘ProductService’, ‘$scope’, function (ProductService, $scope) {

// Create a new product
$scope.createProduct = function() {
var payload = {
name: ‘Shirt’,
color: ‘red’,
size: ‘small’
};
ProductService.create(payload, function(data) {
// do something which you want with response
});
};

// Get a single product
$scope.getProduct = function() {
ProductService.get({id: 1234}, function(data) {
// do something which you want with response
});
};

// Update a product
$scope.updateProduct = function() {
ProductService.update({id: 1234,color:blue}, function(data) {
// do something which you want with response
});
};

// Delete a product
$scope.deleteProduct = function() {
ProductService.remove({id: 1234}, function(data) {
// do something which you want with response
});
};

}]);
[/js]

So in this way we can quickly create a Single Page Applications which involve CRUD operations.

Hope this helps.

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Abdul Samad

    angular.module(‘mytodoApp.services’, []).factory(‘Api’, [‘$resource’, function($resource) {
    return $resource(‘http://localhost:8000/api/v1/quotes/:id’, { id: ‘@_id’ }, {
    update: { method: ‘PUT’ }
    });
    }]);

    Getting error while updating record.
    (index):1 XMLHttpRequest cannot load http://localhost:8000/api/v1/quotes/11. Response for preflight has invalid HTTP status code 405

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *