$resource is a factory (included in the ngResource module, but NOT in the original AngularJS package) allowing to create objects capable to interact with REST resources, via calls of GET, POST, DELETE, POST type, on http endpoints.

Prerequisites

You need to download ngResource and inject its dependencies in your Angular application. It can be downloaded from here (https://github.com/angular/angular.js/) or you can remotely include the package, setting the proper Angular version to be used:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-resource.js">

Now you need to inject ngResource in your AngularJS app:

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

Getting started

$resource allows the definition of resources on which perform classic CRUD operations. If you need to inquiry an endpoint related to certain products, you can use the following syntax:

var Product = $resource('/product/:id');
Product.get({id: 100});

The proposed example will inquiry the endpoint http://mysite.com/produtct/100 using a GET operation.

The methods provided by $resource are:

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

Handling a custom resource

$resource, unlike $http, is able to map remote resources, allowing the definition of further custom methods too.

So you can define a remote resource News, containing various methods, the default ones (such as the cancellation method DELETE or the search method GET), but also a method allowing the social network subscription, i.e. a "subscribe" method, using POST operations.

angular.module('movieApp.services', [])
    .factory('NewsRest', function($resource) {
    return $resource('http://my-endpoint/news/:id', null, {
      subscribe: {
        method: 'POST',
        params: {'facebook': true}
      }
    });
  });

Here you are an usage example of the service News injected into a controller:

angular.module('myApp.controllers', [])
  .controller('NewCtrl', ['$scope', '$stateParams', 'NewsRest', function($scope, $stateParams, NewsRest) {
	  
    $scope.getNews = function() {
     NewsRest.get({id: $stateParams.id}, function(data) {
      $scope.news = data;
     });
    };
    
    $scope.subscribe = function() {
     NewsRest.subscribe({id: $stateParams.id}, function(data) {
      $scope.subscribed  = true;
     });
    };
  }]);

Gabriele Mittica

Developer at Corley S.r.l , Website , Git home page , @gabrielemittica , Linkedin profile
Passionate startupper, Cloud developer and amstaff lover. Worldwide geekka traveler!

All articles by Gabriele Mittica

Comments

comments powered by Disqus

cloudparty

Follow Us