The main question - is it possible? I tried with no luck..
main app.js
...
var app = angular.module('myApp', ['services']);
app.config(['customProvider', function (customProvider) {
}]);
...
provider itself
var services = angular.module('services', []);
services.provider('custom', function ($http) {
});
And I've got such error:
Uncaught Error: Unknown provider: $http from services
Any ideas?
Thanks!
Angular framework has a 2 phase initialization process:
During the config
phase all of the providers are initialized and all of the config
sections are executed. The config
sections may contain code which configures the provider objects and therefore they can be injected with provider objects.
However, since the providers are the factories for the service objects and at this stage the providers are not fully initialized/configured -> you cannot ask the provider to create a service for you at this stage -> at the configuration stage you cannot use/inject services.
When this phase is completed all of the providers are ready (no more provider configuration can be done after the configuration phase is completed).
During run
phase all the run
sections are executed. At this stage the providers are ready and can create services -> during run
phase you can use/inject services.
$http
service to the provider initialization function WILL NOT work//ERRONEOUS angular.module('myModule').provider('myProvider', function($http) { // SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase) ... this.$get = function() { // code to initialize/configure the SERVICE goes here (executed during `run` stage) return myService; }; });
Since we are trying to inject the $http
service into a function which is executed during the config
phase we will get an error:
Uncaught Error: Unknown provider: $http from services
What this error is actually saying is that the $httpProvider
which is used to create the $http
service is not ready yet (since we are still in the config
phase).
$http
service to the service initialization function WILL work://OK
angular.module('myModule').provider('myProvider', function() {
// SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase)
...
this.$get = function($http) {
// code to initialize/configure the SERVICE goes here (executed during `run` stage)
return myService;
};
});
Since we are now injecting the service into the service initialization function, which is executed during run
phase this code will work.
This might give you a little leverage:
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
But be careful, the success/error callbacks might keep you in a race-condition between the app start and the server response.
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