javascriptangularjsdependency-injectionangularjs-serviceangularjs-provider

How to inject $resource into provider?


I've inherited the following code, and I need to get $resource injected into the service. I'm new to AngularJS and not finding the documentation very helpful. Everything I've tried has failed. Any ideas?

(function (angular) {

angular.module('myModule')
    .provider('myService', [myServiceProvider]);

function myServiceProvider() {
    ...
}

Thanks.


Solution

  • You don't have access to the dependencies inside provider function because run at config phase. You could get them available by injecting $injector service inside your provider function.

    But better and cleaner way would be just inject dependency inside it inside provider $get function directly.

    Code

    (function (angular) {
    
        angular.module('myModule')
            .provider('myService', [myServiceProvider]);
    
        function myServiceProvider() {
            this.$get = function($resource){
                //you could have access here to $resource
                //create $resource object here and return it.
                this.getData = function(){
                    return $resource('http://example.com/resource);
                }
            }
        }
    )();