如何使用Angularjs将依赖项注入提供程序中? [英] How to inject dependencies into a provider using Angularjs?
本文介绍了如何使用Angularjs将依赖项注入提供程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以通过提供者方法进行DI?
Is it possible to do DI in a provider method?
在此示例中
angular.module('greet',[])
.provider('greeter',function() {
this.$get=function() {
};
})
.service('greeterService',function($http){
console.log($http);
})
;
将$http
注入服务似乎是正确的实现,但是在提供者方法中不起作用,并且会引发错误:
Injecting $http
into service appears to be the correct implementation, but it doesn't work in a provider method and it throws an error:
未知提供者:$ http
Unknown provider: $http
provider方法是否可以与DI一起使用以注入服务?
Does the provider method work with DI to inject services?
推荐答案
您当然可以将$http
注入提供程序.只要确保它出现在$get
中,而不是函数构造函数中即可.如下:
You can certainly inject $http
to provider. Just make sure it appears in $get
, not the function constructor. As follows:
angular.module('greet',[]).provider('greeter',function() {
this.$get = function($http) {
};
});
这篇关于如何使用Angularjs将依赖项注入提供程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文