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

走远了吗. 提交于 2019-12-20 11:55:16

问题


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');

回答1:


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



来源:https://stackoverflow.com/questions/17897548/cant-get-service-instance-from-injector-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!