jviotti
jviotti

Reputation: 18939

Unable to inject my provider in config

I have app/providers/weather.js:

angular.module('forecast').provider('Weather', function() {    
  var apiKey;

  this.setApiKey = function(key) {
    if(key) apiKey = key;
  };

  this.$get = function() {
    return {
      ... // Some methods
    };
  };    
});

And I'm trying to inject that into my config block:

angular.module('forecast', ['ngRoute']).config(function(WeatherProvider) {    
  WeatherProvider.setApiKey('hello1234');    
});

However I get:

Uncaught Error: [$injector:modulerr] Failed to instantiate module forecast due to:
Error: [$injector:unpr] Unknown provider: WeatherProvider

The strange thing is that I can successfully inject Weather into the controllers and have access to the methods in this.$get.

My index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Forecast</title>
</head>
<body ng-app="forecast">

  <section class="content" ng-view></section>

  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>

  <script src="app/app.js"></script>
  <script src="app/controllers/home.js"></script>
  <script src="app/controllers/settings.js"></script>

  <script src="app/providers/weather.js"></script>

</body>
</html>

I'm unable to find out the error reason. I'm running Angular 1.2.8.

Upvotes: 3

Views: 1038

Answers (2)

KayakDave
KayakDave

Reputation: 24676

Your provider needs to be declared as part of the module forecast before you try to inject it.

One approach, that involves the least change to your current code, is to separate out the module declaration and do it first:

angular.module('forecast', ['ngRoute']);

Then use that when you set up config:

angular.module('forecast').config(function(WeatherProvider) {    
  WeatherProvider.setApiKey('hello1234');    
});

Noting that inside your angular.module:

  • Without square brackets you're accessing an existing module
  • With the square brackets you're declaring a new module.

So you're currently declaring the module and doing the config all at once- without the provider having been instantiated.

demo fiddle

Upvotes: 3

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

You are working with one module 'forecast', so in this case we should/have to be sure, that the configuration already has access to the provider. Other words, set this kind of steps:

// I. Module creation
angular.module('forecast', ['ngRoute']) 
  // II. Provider definition
  .provider('Weather', function() {    
    ...
  }
  // III. configuration using already known provider
  .config(function(WeatherProvider) {    
    ...
  })
;

Upvotes: 6

Related Questions