Search code examples
angularjsangular-resourceangular-http

Using GET only requests on API - $http or $resource


If all I am doing is making basic GET requests from an API (not full CRUD), is it better to use $http or $resource?

I see that $resource uses $http under the hood so does that make it overkill? Code is written more streamlined using $resource than $http especially when I add additional GET requests. Below is my example using both. Trying to determine which is better to move forward with. Everything I read seems to point in both directions. Is there an overall accepted consensus?

$resource

/* Data Factory */
myApp.factory('myServ', ['$resource', '$cacheFactory',
 function($resource) {
  return {
    Events: $resource('api/v1/events/:slug', {}, {slug: '@slug', cache: true, method: 'get'})
  };
}]);

$http:

/* Data Factory */
angular.module('myFactory', [])
    .factory('eventRepo', function($http) {
        return {
            Events: function(callback) {
                $http({
                    method: 'GET',
                    url: 'api/v1/events',
                    cache: true
                }).success(callback);
            }
        };
    });

Solution

  • There is not overall consensus the short answer is it depends on your need.....

    I have found as our AngularJs application has grown, service consumption becomes more complex. A good reusable approach that is scalable and flexible is always a good rule of thumb. A good investment in your services architecture goes a long way in making the application easier to implement, maintain, and unit test. I'd recommend reviewing John Papa's style guide to implementing services.

    https://github.com/johnpapa/angular-styleguide


    http://sauceio.com/index.php/2014/07/angularjs-data-models-http-vs-resource-vs-restangular/

    $http is built into Angular, so there’s no need for the extra overhead of loading in an external dependency. $http is good for quick retrieval of server-side data that doesn’t really need any specific structure or complex behaviors. It’s probably best injected directly into your controllers for simplicity’s sake.

    $resouce is good for situations that are slightly more complex than $http. It’s good when you have pretty structured data, but you plan to do most of your crunching, relationships, and other operations on the server side before delivering the API response. Any custom behavior on the client side will need a lot of boilerplate.