AngularJS $http and $resource

AngularJS $http and $resource

I have some web services that I want to call. $resource or $http, which one should I use?
$resource: https://docs.angularjs.org/api/ngResource/service/$resource
$http: https://docs.angularjs.org/api/ng/service/$http
After I read the two above API pages I am lost.
Could you please explain to me in plain English what is the difference and in what situation should I use them? How do I structure these calls and read the results into js objects correctly?

Solutions/Answers:

Solution 1:

$http is for general purpose AJAX. In most cases this is what you’ll be using. With $http you’re going to be making GET, POST, DELETE type calls manually and processing the objects they return on your own.

$resource wraps $http for use in RESTful web API scenarios.


Speaking VERY generally: A RESTful web service will be a 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, you can call a GET to get the resource as a JavaScript object, then alter it and send it back with a POST, or even delete it with DELETE.

… if that makes sense.

Solution 2:

I feel that other answers, while correct, don’t quite explain the root of the question: REST is a subset of HTTP. This means everything that can be done via REST can be done via HTTP but not everything that can be done via HTTP can be done via REST. That is why $resource uses $http internally.

So, when to use each other?

If all you need is REST, that is, you are trying to access a RESTful webservice, $resource is going to make it super easy to interact with that webservice.

Related:  Copy to clipboard using Javascript in iOS

If instead, you’re trying to access ANYTHING that is not a RESTful webservice, you’re going to have to go with $http. Keep in mind, you could also access a RESTful webservice via $http, it will just be much more cumbersome than with $resource. This is the way most people have been doing it outside AngularJS, by using jQuery.ajax (equivalent of Angular’s $http).

Solution 3:

$http makes general purpose AJAX call, in which general means it can include RESTful api plus Non-RESTful api.

and $resource is specialized for that RESTful part.

Restful Api came to prevalent in recent years because the url is better organized instead of random url made up by programmers.

If I use a RESTful API to construct the url, it would be something like /api/cars/:carId.

$resource way to fetch data

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

    // Service
    .factory('FooService', ['$resource', function($resource) {
        return $resource('/api/cars/:carId')
    }]);

    // Controller
    .controller('MainController', ['FooService', function(FooService){
        var self = this;
        self.cars = FooService.query();
        self.myCar = FooService.get('123');

    }]);

This will give you an resource object, which is accompanied with get, save, query, remove, delete methods automatically.

$http way to fetch data

angular.module('myApp', [])

    // Service
    .factory('FooService', ['$http', function($http){
        return {
            query: function(){
                return $http.get('/api/cars');
            },

            get: function(){
                return $http.get('/api/cars/123');
            }
            // etc...
        }

See how we need to define each common operation on RESTFul API. Also one difference is that $http returns promise while $resource returns an object. There are also third-party plugins to help Angular deal with RESTFul API like restangular

Related:  How can I replace a regex substring match in Javascript?

If the API is something like /api/getcarsinfo. All left for us is to use $http.

Solution 4:

I think the answer depends more on who you are at the time you’re writing the code. Use $http if you’re new to Angular, until you know why you need $resource. Until you have concrete experience of how $http is holding you back, and you understand the implications of using $resource in your code, stick with $http.

This was my experience: I started my first Angular project, I needed to make HTTP requests to a RESTful interface, so I did the same research you’re doing now. Based on the discussion I read in SO questions like this one, I chose to go with $resource. This was a mistake I wish I could undo. Here’s why:

  1. $http examples are plentiful, helpful, and generally just what you need. Clear $resource examples are scarce, and (in my experience) rarely everything you need. For the Angular newbie, you won’t realize the implications of your choice until later, when you’re stuck puzzling over the documentation and angry that you can’t find helpful $resource examples to help you out.
  2. $http is probably a 1-to-1 mental map to what you’re looking for. You don’t have to learn a new concept to understand what you get with $http. $resource brings along a lot of nuance that you don’t have a mental map for yet.
  3. Oops, did I say you don’t have to learn a new concept? As an Angular newbie you do have to learn about promises. $http returns a promise and is .thenable, so it fits right in with the new things you’re learning about Angular and promises. $resource, which doesn’t return a promise directly, complicates your tentative grasp on Angular fundamentals.
  4. $resource is powerful because it condenses the code for RESTful CRUD calls and the transformations for input and output. That’s great if you’re sick of repeatedly writing code to process the results of $http yourself. To anyone else, $resource adds a cryptic layer of syntax and parameter passing that is confusing.
Related:  Webhoster inserts a javascript which brokes my code how to remove it?

I wish I knew me 3 months ago, and I’d be emphatically telling myself: “Stick with $http kid. It’s just fine.”

Solution 5:

I Think it is important to emphasize that $resource expects object or array as response from server, not raw string. So if you have raw string (or anything except object and array) as a response, you have to use $http

Solution 6:

When it comes to choose between $http or $resource technically speaking there is no right or wrong answer in essence both will do the same.

The purpose of $resource is to allow you to pass in a template string (a string that contains placeholders) along with the parameters values. $resource will replace the placeholders from the template string with the parameter values those being passed as an object. This is mostly useful when interacting with RESTFul datasource as they use similar principles to define the URLs.

What $http does is to perform the Asynchronous HTTP Requests.