8

I am using angular-route-segment in my angular app and an trying to configure the segments from a json feed.

I have having problems with this, because I can't figure out how to inject $http into the app.config function. This fails with Unknown provider: $http

myApp.config(["$http", "$routeSegmentProvider", function ($http, $routeSegmentProvider) {
   /* setup navigation here calling $routeSegmentProvider.when a number of times */
}

So instead of injecting $http into config, I also tried injecting $routeSegmentProvider into myApp.run

myApp.run(["$http", "$routeSegment", function($http, $routeSegment) {
    /* can use $http here to get data, but $routeSegment is not the same here */
    /* $routeSegment does not have the when setup method */
}]);

I also tried

myApp.run(["$http", "$routeSegmentProvider", function($http, $routeSegmentProvider)

but I get Unknown provider: $routeSegmentProviderProvider <- $routeSegmentProvider

gwin003
  • 7,432
  • 5
  • 38
  • 59
  • You can find your answer here: http://stackoverflow.com/questions/15937267/inject-service-in-app-config – David Bohunek Sep 03 '14 at 12:17
  • @DavidBohunek I think I came across that example before, but I wasn't able to get it to work for some reason. I decided to go with cliff.meyers answer for now. – gwin003 Sep 03 '14 at 12:41

1 Answers1

12

Providers can only be injected in the "config" phase and not the "run" phase. Conversely, a service such as $http will not have been initialized yet in the "config" phase and will only be available in the "run" phase.

A little trick to work around this is to define a variable in the parent function scope so that both the "config" and "run" blocks can have access to it:

var routeSegmentProvider = null;

myApp.config(["$routeSegmentProvider", function ($routeSegmentProvider) {
    routeSegmentProvider = $routeSegmentProvider;
}]);

myApp.run(["$http", function($http) {
  // access $http and routeSegmentProvider here
}]);

I'm not sure if you will encounter problems trying to call $routeSegmentProvider.setup() within the run phase as I haven't tried. In the past I was able to use the same technique to register http response interceptors that depend on some custom services with the $httpProvider.

cliff.meyers
  • 17,666
  • 5
  • 51
  • 66
  • 2
    It works, though this might not be the *best* solution... I decided to go with this for now. Thanks! – gwin003 Sep 03 '14 at 12:42
  • Seems like a hack to use global variables.. Most of you will let this slip because it's front-end JS. – Adam Fowler Dec 16 '15 at 17:14
  • 1
    This code was originally wrapped in an IIFE but I had omitted it for brevity. Nothing about it requires use of global scope, it's just accessed via closure. – cliff.meyers Jun 02 '16 at 15:29