Why can't I get a $location injected into in my config()?

All we need is an easy explanation of the problem, so here it is.

Why does this give me an error:

angular.module('app')
       .config(function($routeProvider, $locationProvider, $httpProvider, $location) {

Uncaught Error: Unknown provider: $location from app

But this line doesn’t?

angular.module("app")
       .factory("SomeResource", 
               function($q, $resource, $http, $location, AuthenticationService, Base64) {

It’s the same app. Can config only get providers and factory only get non-providers?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Only providers and constants may be injected into configuration blocks.

From the angularjs documentation on configuration blocks

  1. Configuration blocks – get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured

  2. Run blocks – get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Essentially the configuration block is where you configure providers before they are injected into controller, services, factories and so on.

angular.module('myModule', []).
 config(function(injectables) { // provider-injector
   // This is an example of config block.
   // You can have as many of these as you want.
   // You can only inject Providers (not instances)
   // into the config blocks.
 }).
 run(function(injectables) { // instance-injector
   // This is an example of a run block.
   // You can have as many of these as you want.
   // You can only inject instances (not Providers)
   // into the run blocks
 });

Method 2

there are two module level ways to inject code:

1) config. This method will run before the injectors are created, and only accepts providers and constants for injection

2) run. This method will run during the app initialization phase and accepts only instances and constants (such as $location).

factory (and service, controller, and directive) are functions which are part of your application. As such they too can only accepts instances(or singletons) and constants.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply