I am newly exposed to AngularJS, so please forgive my ignorance.
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?
$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.
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
).
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
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.
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.
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.
$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 RESTufl 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
.
$reserouce
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 companied with get
, save
, query
, remove
, delete
methods automatically.
$http
way to fetch data
angular.module('myAp', [])
// 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
.