Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend the $http service in angular?

Unfortunately, we're stuck running 1.2.26 (will upgrade to 1.2.28 when it's gemified).

In the meantime, how can I patch (heh) $http so that the short-hand patch method is available? I'm pretty new to the whole service/factory/module thing. I've done hours of searching and can't seem to figure it out.

myApp.factory('patchedHTTP', function($http, BasicService) {
  // $http['patch'] = function(url, data, config) {
  //   return $http(angular.extend(config || {}, {
  //     method: 'patch',
  //     url: url,
  //     data: data
  //   }));
  // };
  var extended = angular.extend(BasicService, {});
  extended.createShortMethodsWithData('patch');
  return extended;
});

Above is the best I've got... and it doesn't do anything XD

like image 283
Volte Avatar asked Sep 29 '15 20:09

Volte


People also ask

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

What is the use of HttpClientModule in Angular?

The HttpClientModule is a service module provided by Angular that allows us to perform HTTP requests and easily manipulate those requests and their responses. It is called a service module because it only instantiates services and does not export any components, directives or pipes.

What is extend in Angular?

Overview. Extends the destination object dst by copying own enumerable properties from the src object(s) to dst . You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular. extend({}, object1, object2) .

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.


1 Answers

You can do this with an angular decorator.

A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. For more information you can check angular documentation.

Example:

var app = angular.module('app');
app.decorator('$http', function ($delegate) {
  // NOTE: $delegate is the original service

  $delegate.patch = function () {
    // do the implementation here
  };

  return $delegate;
});

// usage
app.controller('SomeController', function($http) {
    $http.patch();
});

You can keep this decorator until you upgrade to some newer version and than just safely delete it.

like image 128
S.Klechkovski Avatar answered Sep 29 '22 23:09

S.Klechkovski