Angularjs $Http and $Resource

AngularJS $http and $resource

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

Angular js: what is the difference between $http and $resource

$resource is built on top of $http.

$http is normal ajax, it can be used for any form of web service.

$resource is specifically for RESTful service.

More details on this

AngularJS $http and $resource

how to get Http status code from $resource request

Just use "transformResponse"

return $resource('http://jsonplaceholder.typicode.com/users/:user',user:'@user',{
query: {
method: 'GET',
transformResponse: function (data, headers, status) {
var ret = {data: data, status: status};
return ret;
}}

});

You'll get data in {data} key and "Status Code" (Eg 200,500,403) in {status} key

Using the $resource as alternative to http in Angularjs not working

Look docs: https://docs.angularjs.org/api/ngResource/service/$resource
correct way is

var t = $resource(...);
t.query(successCallback, errorCallback)

Also notice that:

The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.

$resource HTTP status AngularJs

If you are new to Angularjs, I suggest you to use the $http Service:

https://docs.angularjs.org/api/ng/service/$http

// Simple GET request example:
$http({
method: 'GET',
header:{"content-type":"text"},
url: '/baseUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available

console.log(response.status)

}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Otherwise you need to use an interceptor, but to my point of view is currently and overkill:

.factory("Resource", function ($resource, baseUrl) {
var resource = $resource(url, {}, {
get: {
method: 'GET'
interceptor: {
response: function(response) {
var result = response.resource;
result.$status = response.status;
return result;
}
}
}
});

return resource;
});

you can return it from the factory.

Angular $http vs service vs ngResource

Decided I'll formulate this into an answer since in the comments we worked out basically what you wanted to know:

Using $http or $resource the results can still be cached, you pointed out the reasons to use one over the other really in your question. If you have a RESTful interface then using $resource is better since you'll end up writing less boiler-plate code that is common to a RESTful interface, if you're not using a RESTful service then $http makes more sense. You can cache data either way http://www.pseudobry.com/power-up-http-with-caching/

I think putting $http or $resource requests into a service just generally works out better because you want to have access to the data from multiple locations and the service acts as a singleton. So, basically you can handle any kind of caching you want to do there and controllers can all just watch the appropriate services to update their own data. I've found that a combo of $watch in the controllers for data on the service and returning the promises from my service's methods gives me the most flexibility with how to update things in the controller.

I'd put something like this in my controller having the exampleService injected at the top of the controller definition.

angular.module("exampleApp", []).service('exampleService', ["$http", "$q" ,function ($http, $q) {
var service = {
returnedData: [],
dataLoaded:{},
getData = function(forceRefresh)
{
var deferred = $q.defer();

if(!service.dataLoaded.genericData || forceRefresh)
{
$http.get("php/getSomeData.php").success(function(data){
//service.returnedData = data;
//As Mark mentions in the comments below the line above could be replaced by
angular.copy(data, service.returnedData);
//if the intention of the watch is just to update the data
//in which case the watch is unnecessary and data can
//be passed directly from the service to the controller
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else
{
deferred.resolve(service.returnedData);
}

return deferred.promise;
},
addSomeData:function(someDataToAdd)
{
$http.post("php/addSomeData.php", someDataToAdd).success(function(data){
service.getData(true);
});
}
};
service.getData();
return service;
}]).controller("ExampleCtrl", ["$scope", "exampleService", function($scope, exampleService){
//$scope.$watch(function() {return exampleService.returnedData}, function(returnedData){
// $scope.myModel.someData = returnedData;
//});
//if not using angular.copy() in service just use watch above
$scope.myModel.someData = exampleService.returnedData;
}]);

Also here's a nice video from the Angular team on Best Practices that I'm still re-watching and slowly absorbing over time.

http://www.youtube.com/watch?v=ZhfUv0spHCY

Specifically on services vs controllers:
http://www.youtube.com/watch?v=ZhfUv0spHCY&t=26m41s

AngularJs convert $http POST to $resource POST

Define your resource like this:

angular.module('app')
.factory('MyResource', function ($resource) {
return $resource('', {}, {
'calculate': { method: 'POST', url: 'http://localhost:8080/calculate' }
});
});

or this:

angular.module('app')
.factory('MyResource', function ($resource) {
return $resource('http://localhost:8080/calculate', {}, {
'calculate': { method: 'POST' }
});
});

And then you can use it:

MyResource.calculate({}, JSON.stringify(formData), onSuccess, onError);

With first approach you can define different actions with different urls in single resource (url property), which can be useful sometimes, especially when API which you are using is not unified.

Second approach is better when you have the same endpoint and various request methods for it (like in regular RESTfull APIs). There you can just define them with different names (like get, update, delete, etc.).

You can also use resources in a way like:

var result = MyResource.calculate(JSON.stringify(formData));

It's also possible to get access to internal $promise so you can do some more complicated stuff.

What's important from my experience is that you should remember about isArray: true property, when your API returns JSON array.

All details are described here: https://docs.angularjs.org/api/ngResource/service/$resource



Related Topics



Leave a reply



Submit