Search code examples
angularjsangular-decorator

Decorating a service with a method that uses $http


I'm trying to decorate a service with another method. The problem is that method uses $http which I can't inject into the angular.config block because it hasn't been initialised yet.

I thought I could get around this by using $injector as this would only run when the method I add gets called, but this results in the error:

Error: [$injector:unpr] Unknown provider: $http

Here's an example of what I am trying to do:

angular.module('someModule', [])

.config(($provide, $injector)->  
  $provide.decorator('someService', ($delegate)->   
    $delegate.newMethod = ()->
      $http = $injector.get('$http')
      $http.get('someURL')
    return $delegate
  )
)

Later on, only when I call someService.newMethod() do I get the error mentioned above.

Is there any way to do what I'm trying to do?


Solution

  • Apparently the $injector needs to be injected to the decorator as well, so this will fix it:

    angular.module('someModule', [])
    
    .config(($provide, $injector)->  
      $provide.decorator('someService', ($delegate, $injector)->   
        $delegate.newMethod = ()->
          $http = $injector.get('$http')
          $http.get('someURL')
        return $delegate
      )
    )