efarley
efarley

Reputation: 8661

Angular JS $http undefined in $routeProvider

I have the following code in my routeProvider but for some reason $http is coming back undefined. What am I missing?

config(['$routeProvider', function($routeProvider, $http) {
  var routes = ['partial1','partial2'];
  angular.forEach(routes, function(route, key) {
    var defaultUrl = 'partials/' + route + '.html',
        deviceUrl = 'partials/' + route + '.' + getDevice() + '.html';
    $http.get(deviceUrl).
      success(function() {
        $routeProvider.when('/' + route, {templateUrl: deviceUrl, controller: route + 'Ctrl'});
      }).
      error(function(){
        $routeProvider.when('/' + route, {templateUrl: defaultUrl, controller: route + 'Ctrl'});
      });
  });
  $routeProvider.otherwise({redirectTo: '/' + routes[0]});
}]);

Upvotes: 0

Views: 481

Answers (2)

Leonardo Zanivan
Leonardo Zanivan

Reputation: 790

You forgot to annotate $http to the dependency injector.

Besides, it's not possible to inject a service into a configuration.

To workaround this problem, you could also inject $http manually.

Here is a working example:

config(['$routeProvider', function($routeProvider) {
  var routes = ['partial1','partial2'];
  angular.forEach(routes, function(route, key) {
    var defaultUrl = 'partials/' + route + '.html',
        deviceUrl = 'partials/' + route + '.' + getDevice() + '.html';
    var initInjector = angular.injector(['ng']);
    var $http = initInjector.get('$http');
    $http.get(deviceUrl).
      success(function() {
        $routeProvider.when('/' + route, {templateUrl: deviceUrl, controller: route + 'Ctrl'});
      }).
      error(function(){
        $routeProvider.when('/' + route, {templateUrl: defaultUrl, controller: route + 'Ctrl'});
      });
  });
  $routeProvider.otherwise({redirectTo: '/' + routes[0]});
}]);

Upvotes: 3

Prasad K - Google
Prasad K - Google

Reputation: 2584

You cannot inject services in the module config.

But you can move your code into a provider in case you want to do it in config itself.

Upvotes: 1

Related Questions