Joe
Joe

Reputation: 443

Error when using angular.injector() within a service

I'm trying to create a service in angular and within it, to get a service using angular's $injector.get(...). (I know I can inject it, but I want to create it manually).

For some reason, I'm getting this error:

Uncaught Error: [$injector:unpr] Unknown provider:
$rootElementProvider <- $rootElement <- $location <- $urlRouter <- $state <- $location

(function () {
    var $injector = angular.injector(["myApp"]);//Here is where I get the error
    var myService= $injector.get("myService");

    var pseudoService = function(){
        var service = myService;
        return{
            service:service
        }
    }

    app.factory("pseudoService", pseudoService);
}(angular));

Here is a plunker I made. I hope it demonstrates the issue precisely.

plunker

Upvotes: 1

Views: 907

Answers (2)

layonez
layonez

Reputation: 1785

That question already have a great answer on SO

https://stackoverflow.com/a/13403660/2204146

What you need is add 'ng' module first in your injector constructor

angular.injector(['ng', 'plunker']);

Upvotes: 1

Ram_T
Ram_T

Reputation: 8484

See this plunker that contains your code in app.js

https://plnkr.co/edit/5VA5XgbNiCAX0ZcjDADo?p=preview

Now, its working fine.

You are writing injector code where the service is not available and you must add ng explixitly in the angular.injector() function, for more info https://docs.angularjs.org/api/ng/function/angular.injector. That is why you are getting the error

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>

    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
  </body>

</html>

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';


  var $injector = angular.injector(['ng', 'plunker']);
  var a = $injector.get('myService')
  console.log(a);
});

app.factory('pseudoService', pseudoService);

var pseudoService = function(){
    var service = myService;
    myService.sayHello();
    return{
     service:service
    }
}



var myService = function(){
  var sayHello = function(){
    alert("Hello")
  }
  return{
    sayHello:sayHello
  }
}

app.service('myService', myService);

Upvotes: 1

Related Questions