Question

I'm trying to use a service "factory" in service "provider". How is the best way to do it. I'm working with different modules. but it is generates a mistake me when I import the service to the new function. What is the best way to reuse or inject services in a service "provider".

http://jsfiddle.net/aurigadl/facgT/5/

var moduleService = angular.module('templatesServices', []);
moduleService.factory('templateSrv',['$q', function($q){ 
    return {
        data: function(){
            console.log('In factory');
            return 2000;
        }
    }
}])

function  login(templateSrv){
  this.$get     = angular.noop;   
  this.getAcces = function(){
    return 'some data';
  };
}   

login.$inject = ['templatesServices'];

angular.module('loginProvider', ['templatesServices']).provider('login', ['caliopewebTemplateSrv',login]);
Was it helpful?

Solution

Providers are available in a phase before any solid services or other components are ready, so you won't be able to inject your service directly into the provider.

You can, however, inject services into the $get function of your provider, used when you actually instantiate a service. So your loginProvider cannot access templateSrv but your login service can do, so long as the module in which templateSrv is defined 'requires' that in which loginProvider is defined. It appears to be doing this in your example (angular.module('loginProvider', ['templatesServices'])) but the fiddle seems very different.

var templateModule = angular.module('templateModule', []);
templateModule.factory('templateSrv',[function(){ 
    return {
        // ...
    };
}]);

function loginProvider(){
    this.$get = ['templateSrv', 'otherService', function(templateSrv, otherService) {
      // Use templateSrv/otherService (from templateModule or loginModule) somehow
    }];
    this.getAccess = function(){
        return 'some data';
    };
}

angular.module('loginModule', ['templateModule'])
    .provider('login', loginProvider);

I don't quite follow your intentions so I can't give much more information, but I hope this helps.

Sources:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top