Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject dependencies into a provider using Angularjs?

Tags:

angularjs

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?

like image 616
Chung Avatar asked Oct 04 '13 00:10

Chung


People also ask

Does AngularJS have Dependency Injection?

Dependency Injection is pervasive throughout AngularJS. You can use it when defining components or when providing run and config blocks for a module.

How is Dependency Injection done in AngularJS?

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.

What is Dependency Injection in AngularJS with example?

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.


2 Answers

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) {    }; }); 
like image 59
Buu Nguyen Avatar answered Oct 11 '22 14:10

Buu Nguyen


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.

like image 23
z0r Avatar answered Oct 11 '22 12:10

z0r