AngularJS $http and $resource
JavascriptWeb ServicesAngularjsJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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
).
Solution 2 - Javascript
$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 3 - Javascript
$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
.
Solution 4 - Javascript
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:
$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.$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.- 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.then
able, 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. $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."
Solution 5 - Javascript
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 - Javascript
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.
Solution 7 - Javascript
resource service is just useful service for working with REST APSIs. when you use it you don't write your CRUD methods (create,read,update and delete)
As far as I see it, resource service is just a shortcut, you can do anything with http service.
Solution 8 - Javascript
One thing i noticed when using $resource over $http is if you are using Web API in .net
$resource is tied up into one controller that execute a single purpose.
$resource('/user/:userId', {userId:'@id'});
[HttpGet]
public bool Get(int id)
{
return "value"
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
While $http could be of anything. just specify the url.
$http.get - "api/authenticate"
[HttpGet]
public bool Authenticate(string email, string password)
{
return _authenticationService.LogIn(email, password, false);
}
it's just my opinion.
Solution 9 - Javascript
The $resource service currently does not support promises and therefore has a distinctly different interface to the $http service.
Solution 10 - Javascript
What I could understand is that if you are having a RESTFUL resources to manage, using $resource
will let you define the resource once in code, and use the resource for multiple operations on the resource. This increases the readability and maintainability of the code.
If you just want to have general purpose calls not managing it like post, delete, update, you may go with $http
or $resource
(as you prefer).