angularjs - How can I extend the $http service in angular? -
unfortunately, we're stuck running 1.2.26 (will upgrade 1.2.28 when it's gemified).
in meantime, how can patch (heh) $http short-hand patch
method available? i'm pretty new whole service/factory/module thing. i've done hours of searching , can't seem figure 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 best i've got... , doesn't xd
the module.decorator
has been added module api in version 1.4. that's why not working in 1.2.x.
please find below working demo or here @ jsfiddle.
it took me while implement patch method because i've missed return promise of $http
. should working.
angular.module('patchdemo', []) .config(function ($provide) { $provide.decorator('$http', function ($delegate) { // note: $delegate 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>
Comments
Post a Comment