0

I've got a very simple angular app that I can not figure out what is wrong with. The code is on plunkr here: http://plnkr.co/edit/QQkP2HB6VGv50KDdBPag?p=preview and generates the error: Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:unpr] Unknown provider: testService

The code is below

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>simple problem I can not figure out</title>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script>

    <script type="text/javascript">

        (function() {
            'use strict';

            var myAppModule = angular.module('myApp', []);

            myAppModule.service('testService', function (testService) {
            });

            myAppModule.config(['testService',
                function (testService) {
            }]);

        })();

        </script>

    </head>
    <body >
    <div ng-app="myApp">
        <div>
           myApp Here
        </div>
    </div>
    </body>
    </html>
5
  • Is there a reason you are injecting the service into itself? Commented Jan 13, 2015 at 20:13
  • 1
    myAppModule.service('testService', function (testService) { ? You are trying to inject testService in testservice? And you cannot inject testService inside config because service would not have been instantiated yet. Commented Jan 13, 2015 at 20:13
  • @Mathew-green I'm trying to create the service and then use it in the module. clearly I'm not doing that. How do I create the service first, then use it in the module.config? Commented Jan 13, 2015 at 20:23
  • 1
    You may not use a service during the configuration phase. Only providers of services. After the configuration phase, services are instantiated and injected when they need to be. Commented Jan 13, 2015 at 20:24
  • @PeterKellner Why do you need to inject a service in a config phase. Probably if you state that there could be a solution. You might be trying to solve an X/Y problem. Commented Jan 13, 2015 at 20:41

1 Answer 1

2

There are multi phase in angular bootstraps process. in config phase you can just inject provider. for example you can use this code:

        myAppModule.config(['testServiceProvider',
            function (testServiceProvider) {
            }]);

To get more information please check this link:

https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection#configuring-providers

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Himen. I get so frustrated with exceptions like "during the config phase, only providers can be injected (with the exception of the services in the AUTO module--$provide and $injector)" I need to dig in more and really understand what is happening under the covers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.