ChatGPT解决这个技术问题 Extra ChatGPT

AngularJS $http and $resource

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?

$resource is built on top of $http, and provides further abstraction from the underlying communications. It requires also a REST end-point that conforms to the $resource patterns. Since you're asking, my suggestion is to start with $http, get acquainted, and then later on see if you can shift to $resource.
Thanks for the answer. So, in what situation is $http ever preferred over $resource apart from that I can get acquainted to the api?

b
bluehallu

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


nice answer, this should be accepted, not the one on top
It means we have three ways to call RESTful?? Using $resource, $http and jquery.ajax , am i right??
@JakeHuang You can call it even without any library, there are infinite ways to do it. I just exposed the 2 most popular approaches in the AngularJS world and the most common approach outside of it.
May i know what the 2 most popular approaches in the AngularJS are? :p
L
Liam

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


So $resource handles Restful services, that means it can also be used to call normal web services? Since it does GET POST DELETE PUT all that. So, in what situation is $http ever preferred over $resource?
Really anytime you're not dealing with a truly restful endpoint. It adds a lot of functionality you would not need if your endpoint only allowed GET, for example.
@blesh, so using the $resource service would only be idiomatic/good if your REST endpoint supports GET, POST, and DELETE? The docs (docs.angularjs.org/api/ngResource.$resource) show that you get these 3 REST methods with $resource.
@KevinMeredith: Or it any number of method. You can add PUT or anything else you'd like, GET, POST and DELETE are just defaults. If you have an endpoint that deals with the same resource (that's important) for more than one HTTP method, then $resource is a good choice.
Even for a none-RESTful endpoint, I've found it convenient to use $resource for GET and QUERY type data. Given the way the .$promise works well resolve for routing and binding.
M
Mohit

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


This should be the answser.
If the api is /api/getcarsinfo I guess we can still use $resource
This should be the answser. when you said "Also one difference is that $http returns promise while $resource returns an object" 1- does that mean i don`t need to use .then with $resource? 2- also as a frontend person and this might sound silly how can i find out if the api is restful or not? thanks
@shireefkhatab 1. yes, $resource is just a higher level abstraction of $http for RESTFul API connivence. The doc example shows how to use it. 2. It totally depends how your backend guy design the url. If he wants to conform to RESTFul api paradigm, then you are good to go
M
Matthew Marichiba

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


I like your answer, especially the last line. I'm currently going through a shift in using $resource vs $http. The one thing I'd also add is that $resource really only comes in really handy and actually helps when you are using the same API noun, like /user/:userId or /thing. Once you move to /users/roles/:roleId then you're having to modify the $resource url and params on a per verb basis and you might as well be using $http at that point.
Call me schizophrenic for commenting on my own answer, but I thought I'd mention more recent experience. I have been refactoring to eliminate $resource and switch to $http in places. I cannot emphasize enough how much I wish wish wish I had never met $resource. I have probably wasted more than a week chasing down the nuances of $resource over the months. $http is so easy and straightforward, any gain to be had in $resource was thoroughly wiped out by the learning curve.
s
sparrkli

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


Does that mean $http does not support object and array? Just wanted to clarify.
I believe $http supports objects, arrays and strings - I'd need confirmation on that though
@Shardul , i understood that $http deals with any kind of response but $resource deals with objects and arrays only.
Not true, you can still use $resource for returning a String. Use 'transformResponse' in your frontend code to wrap the returned String in an object.
D
Dalorzo

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.


This is a good answer because it points out that $http is what powers the requests from $resource, and that either do essentially the same thing.
@Dalorzo So you mean to say $resource cannot perform Asynchronously? Just wanted to clarify
No, what I pointed out is that at the end $http is the simplest way to perform an Asynchronous HTTP Requests and what $resource essentially does the same but with different parameters
j
john Smith

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.


I'm not sure I would classify $resource as a shortcut. It's a wrapper for $http, so using $http directly would be "shorter". It is a way for you to configure $http so that you have potentially less code when utilizing $http. In one case $http.get('/path/to/thing', params) versus myResource.get(params) plus actually doing the configuration for myResource. More code up front and only really works swimmingly with the same API noun. Otherwise, you're coding just as much as if you used $http.
j
jayson.centeno

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.


f
firdous

The $resource service currently does not support promises and therefore has a distinctly different interface to the $http service.


The $resource service does support promises, but it does not return a $promise directly like $http does. You have to do it like var myResource = $resource(...config...); then somewhere else in the service you do return myResource.get(..params...) or you can do var save = myResource.save(); save.$promise.then(...fn...); return save;
D
David Duran

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