Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $http and $resource

People also ask

What is $resource in AngularJS?

Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

How do we pass data and get data using http in angular?

get request Method Syntax: $http. get(url, { params: { params1: values1, params2:values2, params3:values3...... } });


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.

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).


$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.


$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


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


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.

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