Search code examples
angularjsangularjs-routingangularjs-factory

AngularJS - unknown provider when creating a factory


I have an issue that I can't resolve... I have created a module and a factory. Now I try to use the factory in the config block for routing but I have an "unknown provider" error. Debugging, I have simplified the code to try and get the point, but I still have the very same error. I have the following code:

(function(){
  'use strict';
  var app = angular.module('testModule', [
      'ngResource',
      'ui.router'
  ]);

  app.factory('testFct', [function () {
    return {
      a: "bienvenue"
    };
  }]);

  app.config(['testFct','$stateProvider','$urlRouterProvider',function(testFct, $stateProvider, $urlRouterProvider) {}]);


})();

and the error I'm getting:

Error: [$injector:modulerr] Failed to instantiate module testModule due to:
[$injector:unpr] Unknown provider: testFct

Note : I have tried to inject testFctProvider instead and THIS works but I cannot then use my factory itself


Solution

  • You cannot inject services to config block, only providers.

    You need to declare a provider for your service to be able to add interactions between him and the stateProvider / urlRouterProvider.

    If you dont need these interactions and only need to initialize something, use a run block instead of a config one where you'll inject your service.