Search code examples
angularjsangularjs-service

can't get service instance from $injector.get()


I define a customer service named "greeting", but can't get the instance from $injector.get('greeting'). It will throw such error: Unknown provider: greetingProvider <- greeting. So which is the right way to get it? Following is the code:

var app = angular.module('myDI', []);
app.config(function($provide){
    $provide.provider('greeting', function(){
        this.$get = function(){
             return function(name) {
                 console.log("Hello, " + name);
            };
        };
    });
});

var injector = angular.injector();
var greeting = injector.get('greeting');
greeting('Ford Prefect');

Solution

  • You need to create the injector from the module.

    var app = angular.module('myDI', []);
    app.config(function($provide){
        $provide.provider('greeting', function(){
            this.$get = function(){
                 return function(name) {
                     console.log("Hello, " + name);
                };
            };
        });
    });
    var injector = angular.injector(['myDI', 'ng']); //Add this line
    var greeting = injector.get('greeting');
    greeting('Ford Prefect');
    var injector = angular.injector();
    

    Try it here. FIDDLE