1

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

Nicolas
  • 75
  • 9

1 Answers1

3

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.

Pierre Gayvallet
  • 2,933
  • 2
  • 23
  • 37
  • or just move that code to `run` block instead, where you can use services. – vittore Aug 13 '15 at 16:39
  • Thanks, in fact I need to call al web service to check the authentication of the user in the resolve block. I have tried to create a provider also, but I still get the "unknown provider"... – Nicolas Aug 13 '15 at 16:40
  • You will not be able to do this in a config block because you wont be able to access the $http service, only the $httpProvider. config/run block and ajax call during app initialization is somethings angular really sucks at... – Pierre Gayvallet Aug 13 '15 at 16:42
  • To check for user rights before allowing him to access a route, you will need to check the "resolve" option of routes ( doc for angular, but ui-router has the same option : https://docs.angularjs.org/api/ngRoute/provider/$routeProvider ) – Pierre Gayvallet Aug 13 '15 at 16:45
  • Either this, or a custom interceptor for the route events, but this is starting to be dirty. – Pierre Gayvallet Aug 13 '15 at 16:45
  • ok thanks for the help ! I am going to come back to the "old way", using standard functions outside of factories... this used to work, but I was engaged in a refactoring effort :) useless one on this point :) – Nicolas Aug 13 '15 at 16:46