Is it possible to do DI in a provider method?
In this example
angular.module('greet',[]) .provider('greeter',function() { this.$get=function() { }; }) .service('greeterService',function($http){ console.log($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:
Unknown provider: $http
Does the provider method work with DI to inject services?
Dependency Injection is pervasive throughout AngularJS. You can use it when defining components or when providing run and config blocks for a module.
Angular's Dependency Injection is based on providers, injectors, and tokens. Every Angular module has an injector associated with it. The injector is responsible to create the dependencies and inject them when needed. Dependencies are added to the injector using the providers property of the module metadata.
Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable.
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) { }; });
You can inject constants and other providers into a provider. Not services or factories - with one exception. It seems that you can inject the $injector
service into a provider - at least, you can in AngularJS 1.3.16.
.provider('foo', ['$injector', function ($injector) { var messagePrefix = $injector.get('msgPrefix'); this.message = ''; this.$get = function() { var that = this; return function() { return messagePrefix + that.message; } }; }])
You can use the injector outside the $get
method, but you still can't get services from it at configure time.
See here for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With