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