我定义了一个名为“ greeting”的客户服务,但是无法从$ injector.get('greeting')获取实例。它将引发这样的错误:未知提供者:greetingProvider
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');
最佳答案
您需要从模块创建注射器。
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
关于angularjs - 无法从$ injector.get()获取服务实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17897548/