4

I would like to create a service that will create an interface to AngularJS's $http based on this. I would like to use dependency injection to inject the service without re-writing individual function calls and keeping the code clean. To do this I am providing a common service that creates a variable to the $http object like this:

commonService = function(...) {
return {
    ...
    $http: $http
}

Then I use common.$http everywhere in the code. To change $http from AngularJS $http to my httpService, I need to only change it in one place. httpService looks like this:

function httpService($http, $q, pendingRequests, $interval) {
var get = function(url) {
    ...
    return requestPromise;
};

var service = {
    get:get
};

return service;

}

This works for calls to $http.get() but what about calls to $http({method:'get', url:'...'}); ?

Is it possible to provide the () method, which is really httpService()()? Otherwise it would call the AngularJs method httpService().

Community
  • 1
  • 1
jmbmage
  • 2,487
  • 3
  • 27
  • 44
  • I think you are looking for decorators https://docs.angularjs.org/api/auto/service/$provide#decorator – major-mann Sep 02 '14 at 14:02
  • 1
    `()` isn't a method. It's just invoking a function that was returned. If that's what you want, then just return a function that performs whatever action you need. – cookie monster Sep 02 '14 at 14:02
  • @major-mann how does that work? like `$provide.decorator((), $http);`? – jmbmage Sep 02 '14 at 14:09
  • Here is a blog entry which should get you going http://solutionoptimist.com/2013/10/07/enhance-angularjs-logging-using-decorators/ :) – major-mann Sep 02 '14 at 14:10
  • Basically $provide.decorator( '$http', [ "$delegate", function( $delegate ) {} ... inside, $delegate is the original $http. – major-mann Sep 02 '14 at 14:12

1 Answers1

2

You can just return a function instead of an object. You can add the properties to your function

function httpService($http, $q, pendingRequests, $interval) {
   var get = function(url) {
      ...
      return requestPromise;
   };

  // Instead of returning an object, return a function
  var service = function() {
    // do whatever you want here
  };

  service.get = get;

  // Add more properties to service as needed

  return service;
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217