How can I extend the $ http service in angular?

Unfortunately, we launched 1.2.26 (it will be updated to 1.2.28 when it is shown).

At the same time, how can I pay (heh) $ http so that a short patch method is available? I am new to the whole service / factory / module. I have been looking for many hours and do not seem to understand.

 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 have ... and XD does nothing

+6
source share
2 answers

module.decorator was added to the module API in version 1.4. That is why it does not work in 1.2.x.

Below is a working demo or here in jsfiddle .

It took me a while to implement the patch method because I skipped to return the promise of $http . But now it should work.

 angular.module('patchDemo', []) .config(function ($provide) { $provide.decorator('$http', function ($delegate) { // NOTE: $delegate is the original service $delegate.patch = function(url, data, config) { var paramsObj = angular.extend({}, config || {}, { method: 'PATCH', url: url, data: data }); return $delegate(paramsObj); } return $delegate; }); }) .controller('MainController', MainController); function MainController($http) { console.log($http.patch); //$http({method: 'PATCH', url: 'http://jsonplaceholder.typicode.com/posts/1', data: {title:'foo'}}); //>>>>>working long version of patch $http.patch('http://jsonplaceholder.typicode.com/posts/1', { title: 'foo' }).then(function(response) { console.log(response); }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.26/angular.js"></script> <div ng-app="patchDemo" ng-controller="MainController"></div> 
+3
source

You can do this with the angular decorator.

The service decorator intercepts the creation of a service, allowing it to override or change the behavior of the service. The object returned by the decorator may be the original service or a new service object that replaces or wraps and delegates the original service. For more information, you can check the 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 save this decorator until you upgrade to the new version and simply remove it.

+4
source

All Articles