Reputation: 523
Snippet 1 does not work. I get Error: [$injector:unpr] Unknown provider: $q
/* Snippet 1*/
var mApp = angular.module('MyApp',[]);
mApp.provider('authProvider', ['$q', function($q) {
this.$get = function(){
authProvider = {};
authProvider.Title = function(){
var deferred = $q.defer();
deferred.resolve("promise resolved");
return deferred.promise;
}
return authProvider;
}
}]);
However, Snippet 2 works. I am confused why that is ? All the factory sample codes i have read, inject the dependency in the first line such as .factory('MyFactory',[$q,function($q) {}]); Why doesnt that style work in the provider code above ? Also, why are we injecting $q below in the GET declaration but not further down in the TITLE declaration.
/* Snippet 2*/
mApp.provider('authProvider', function() {
this.$get = function($q){
authProvider = {};
authProvider.Title = function(){
var deferred = $q.defer();
deferred.resolve("promise resolved");
return deferred.promise;
}
return authProvider;
}
});
Please help!!!
(The code doesn't do anything right now. I am just trying to learn syntax)
Upvotes: 4
Views: 2294
Reputation: 48968
All the factory sample codes i have read, inject the dependency in the first line such as
.factory('MyFactory',[$q,function($q) {}]);
Why doesn't that style work in the provider code above ?
This graphic has always helped me understand the difference between a provider
and a factory
:
source: simplygoodcode.com
The factory
function is the $get
function of the provider
. Before injection, the provider
constuction function can configure the $get
function. The $get
function is where injection happens.
The provider
construction function isn't injectable. That's why you get that error. The $get
function is injectable and that is the function that you specify with factory
. factory
is just syntactic sugar for creating a provider
with an empty constructor function.
Upvotes: 2
Reputation: 2280
you can't do direct DI in provider
, when you are using provider
you have to inject your component in $get
.
Reason you cannot inject dependency into the provider
directly is that the provider
runs during the module loading phase whereas the $get
is run when instantiating the service you are providing.
You can not use any service during the loading/configuration phase of your modules.
Upvotes: 3