本文介绍了无法从 $injector.get() 获取服务实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个名为greeting"的客户服务,但无法从 $injector.get('greeting') 获取实例.它会抛出这样的错误:Unknown provider: greetingProvider .那么获取它的正确方法是什么?代码如下:

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

推荐答案

您需要从模块创建注入器.

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

在这里试试.FIDDLE

这篇关于无法从 $injector.get() 获取服务实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:52