CodyBugstein
CodyBugstein

Reputation: 23322

$http(config) vs $http.get(...): What is the difference?

According to the Angular documentation for $http, it seems that the constructor

$http(config)

and the functions

$http.get(...)

both return the same things - HttpPromises.

So what is the difference between them? Or are they just two ways to write the exact same thing?

Upvotes: 1

Views: 1428

Answers (1)

raina77ow
raina77ow

Reputation: 106385

$http.get(...), as said in the doc you gave link to, is a shortcut method to perform GET request. You won't be able to make any other type of request with $http.get - GET only. Note that POST, PUT, HEAD and DELETE have their corresponding shortcut methods too.

All these methods, however, are essentially the $http(config) calls - with method parameter pre-specified. Here's how it's done (1.3.6 source):

createShortMethods('get', 'delete', 'head', 'jsonp');
// ...

function createShortMethods(names) {
  forEach(arguments, function(name) {
    $http[name] = function(url, config) {
      return $http(extend(config || {}, {
        method: name,
        url: url
      }));
    };
  });
}

Still, sometimes it's more convenient to use $http(config) syntax - for example, if one has to choose the request method based on some external conditions that should be easy to switch. Note that if you don't specify method property in config, GET is used:

function $http(requestConfig) {
  var config = {
    method: 'get',
    transformRequest: defaults.transformRequest,
    transformResponse: defaults.transformResponse
  };
  // ... some checks skipped
  extend(config, requestConfig);
}

Upvotes: 4

Related Questions