Angular Inject $http into config or provider into run - angularjs

I am using angular-route-segment in my angular app and an trying to configure the segments from a json feed.
I have having problems with this, because I can't figure out how to inject $http into the app.config function. This fails with Unknown provider: $http
myApp.config(["$http", "$routeSegmentProvider", function ($http, $routeSegmentProvider) {
/* setup navigation here calling $routeSegmentProvider.when a number of times */
}
So instead of injecting $http into config, I also tried injecting $routeSegmentProvider into myApp.run
myApp.run(["$http", "$routeSegment", function($http, $routeSegment) {
/* can use $http here to get data, but $routeSegment is not the same here */
/* $routeSegment does not have the when setup method */
}]);
I also tried
myApp.run(["$http", "$routeSegmentProvider", function($http, $routeSegmentProvider)
but I get Unknown provider: $routeSegmentProviderProvider <- $routeSegmentProvider

Providers can only be injected in the "config" phase and not the "run" phase. Conversely, a service such as $http will not have been initialized yet in the "config" phase and will only be available in the "run" phase.
A little trick to work around this is to define a variable in the parent function scope so that both the "config" and "run" blocks can have access to it:
var routeSegmentProvider = null;
myApp.config(["$routeSegmentProvider", function ($routeSegmentProvider) {
routeSegmentProvider = $routeSegmentProvider;
}]);
myApp.run(["$http", function($http) {
// access $http and routeSegmentProvider here
}]);
I'm not sure if you will encounter problems trying to call $routeSegmentProvider.setup() within the run phase as I haven't tried. In the past I was able to use the same technique to register http response interceptors that depend on some custom services with the $httpProvider.

Related

Angular Controller can inject service just fine but $injector.get can't?

I have an extremely edge case scenario where I have a callback method I have to define during config. Which means no scope, no factories, etc... My work around is to use the root injector ($injector) and get my other modules at runtime.
However, when I call $injector.get('myServiceName') in my call back (after the application is running) I get "unknown provider". The same service has no problem (and actually is) being injected into a before my line of code is running. If I call $injector.get("myServiceNameProvider") then I can get the provider back in my callback.. But another service that only has a factory I can't get at all.
So in this extremely bad practice, how can I snag the service I configured. Heck I can't even seem to get $rootScope..
Angular inits providers first, then factories/services - services are not available in app.config.
You can deo like this:
app.config(...
window.on('scroll', function() {
// this is executed later
$injector.get()...
})
Or use app.run where services are available.
I think I had similar problem few months ago... I need to construct breadcrumbs, but they had to be created in config phase (ui-router). I have done it like this (breadcrumbs-generation-service.provider.js):
var somethingYouHaveToHaveLater = undefined;
function BreadcrumbsGenerationService () {
this.createStateData = createStateData;
function createStateData (arg) {
somethingYouHaveToHaveLater = arg;
};
}
function BreadcrumbsGenerationServiceProvider () {
this.$get = function BreadcrumbsGenerationServiceFactory () {
return new BreadcrumbsGenerationService();
}
}
angular
.module('ncAdminApp')
.provider('BreadcrumbsGenerationService', BreadcrumbsGenerationServiceProvider);
Because service is used inside Angular configs, needs to be injected as provider to be available in config phase: Similar SO Question. Despite the fact is registered as BreadcrumbsGenerationService needs to be injected as BreadcrumbsGenerationServiceProvider to config phase and used with $get():
BreadcrumbsGenerationServiceProvider.$get().createStateData(someParams);
But in controller, inject it without Provider suffix (BreadcrumbsGenerationServic) and it behaves as normal service.

How to call a service by his name at controller runtime in angularJs?

I am passing the service name from one controller to another controller as argument in angularjs. When I receive that variable in the second controller and use it as service name then I get an error i.e. serviceNameVariable.get is not a function. So my question is that, How can I use a variable as service name in a controller ?
It's not that difficult to get a service by his name.
Dependency injection can also be done at runtime in angular :
angular.module("someApp").controller("childController", [
"$injector",
function($injector){
var serviceName = "someServiceName";
var service = $injector.get(serviceName);
service.executeAction(someParams);
}
]);
Look at Angular's $injector service which allows you to dynamically retrieve your own or native angular modules anywhere:
$injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.
We inject the $injector service like any other:
app.controller('ctrl', function ($injector) {
var serviceNameVariable = '$http'; // or some input
var service = $injector.get(serviceNameVariable);
// Use the 'injected' service, in this case the $http#get method:
service.get('http://endpoint');
});

Adding an attribute to a provider after config

I am using ng-flow, to upload files with a servlet but as I was securing the servlet I realized I need to pass the token to the headers so It would work and be secure. The problem is that ng-flow's settings are declared on a provider inside a .config box. And as I learned the hard way you can't inject stuff on .config because the injections are created after config.
angular.module('UploadModule', [ 'ngResource','flow' ,'AuthModule']).config(
[ 'flowFactoryProvider',function(flowFactoryProvider,$provide) {
//AuthService.getKeycloak();
flowFactoryProvider.defaults = {
target : '/ng-flow-java/upload',
permanentErrors : [ 500, 501 ],
maxChunkRetries : 1,
chunkRetryInterval : 5000,
simultaneousUploads : 4,
progressCallbacksInterval : 1,
withCredentials : true,
method : "octet",
headers : {'Authorization', 'Bearer + ' token}
};
flowFactoryProvider.on('catchAll', function(event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
} ]);
I am really new to angular so I am looking for a way reassemble this code so I can add the token from my user.
Thanks
I think I don't understand what exactly is the problem but:
Actually each angular service x has a provider function. This function is a constructor function and will be instanciated by angular and its result is injectable in config blocks with name xProvider. This object should have a special $get function which is actually the factory for the service, meaning that it will be called to get the single instance of the service, when it is injected into some controller, directive, etc for the first time.
So you should think of an angular service as a function like this:
function SomeServiceProvider(){
this.$get = function SomeServiceFactory(){
}
this.someConfigurerFunction(){
}
}
which is registered with provider API:
someModule.provider("someService", SomeServiceProvider);
and angular internally will execute something like new SomeServiceProvider() and save it and makes in injectable in config blocks under the name of someServiceProvider. Further, when you ask for "someService", in a directive, controller, etc, for the first time, the injector will call something like new someServiceProvider.$get(), return its result to you and saves it in its registry for further injections.
When you use other higher level angular module APIs, like factory or service like this:
someModule.factory("anotherService", function AnotherServiceFactory(){
// code for creating service
});
the provider function is generated for you with only a $get function, so you don't see the provider function, but still there is a provider function for your service like this:
function AnotherServiceProvider(){
this.$get = AnotherServiceFactory;
}
and it's used as constructor to instantiate anotherServiceProvider which is injectable in config blocks.
You can find out good information about angular services in angular documentations for $provide and angular documentations for module API
Side Notes:
Good services usually come with a provider that enables you to configure service, but if not, you still can intercept the creation of the service with decorators and make service to work as you want.
The process of instantiating objects like services is not exactly like what I've said here (I mean new ...), but it doesn't changes the concepts described here.

AngularJS two different $injectors

Today I found, that $injector injected to config or provider is different from $injector injected to service, factory or controller.
And get() function from this $injectors works differently.
$injector from config or provider, can't get() any service! $injector.get('myService') throws Error: [$injector:unpr] Unknown provider: myService, but $injector.has('myService') return true. That's very very strange.
$injector from service or controller works normally.
Here is a code sample for better understanding:
angular.module('app', [])
.provider('myProvider', function ($injector) {
this.$get = ['$injector', function (serviceInjector) {
return {
providerInjector: $injector,
serviceInjector: serviceInjector
};
}];
})
.service('myService', function () {})
.controller('myCtrl', function ($scope, myProvider) {
var providerInjector = myProvider.providerInjector;
var serviceInjector = myProvider.serviceInjector;
console.log(providerInjector === serviceInjector); // -> false
console.log(serviceInjector.has('myService')); // `serviceInjector` has `myService`
console.log(getMyService(serviceInjector)); // `serviceInjector` can get `myService`
console.log(providerInjector.has('myService')); // `providerInjector` has `myService` too!
console.log(getMyService(providerInjector)); // but `providerInjector` can't get `myService`! =(
function getMyService(injector) {
try {
injector.get('myService');
return "OK";
} catch (e) {
return e.toString();
}
}
});
Here is a plunker to play
Can anybody explain why there is two different injectors?
And how can I use $injector from provider/config to inject service(after service was initialized, of course)?
P.S. I use angular 1.3.13
I found this issue on github: https://github.com/angular/angular.js/issues/5559
In the config function, $injector is the provider injector, where in the run function, $injector is the instance injector.
One's the $injector at the config stage (only providers and constants accessible), and one's the $injector at the run stage. The confusion may be that you're thinking the $injector modifies itself to include the new stuff as it crosses the line from config to run, but that's not true. They're two separate (although related) objects, with their own caches of instances.
A more in-depth reason for this dichotomy will probably come from a deep learning of the $injector internals, but it seems like it's been DRY-ed pretty hardcore, and the two types of injectors share almost all the same behavior, except in how they deal with "cache misses" in their instance caches.
We are going to overhaul the injector in v2, so this will get fixed there (getting rid of the config phase is one of the objectives of the injector v2).
Seems like there is really two different injectors, and angular developers will not fix that behavior(in versions <2.0). And nobody added a note about that aspect to $injector docs for some reason.
I was unable to find a way how to really get instance injector inside a configuration block without hacky tricks. So, I write a cute provider to solve that kind of problems.
.provider('instanceInjector', function () {
var instanceInjector;
function get() {
return instanceInjector;
}
function exists() {
return !!instanceInjector;
}
angular.extend(this, {
get: get,
exists: exists
});
this.$get = function ($injector) {
instanceInjector = $injector;
return {
get: get,
exists: exists
};
}
})
// We need to inject service somewhere.
// Otherwise $get function will be never executed
.run(['instanceInjector', function(instanceInjector){}])
Ok. After reading your comments, here is my answer.
I edited code in plunk to make it work, when invoking the providerInjector.get() the code should be as follows:
$scope.getMyServiceFromProviderInjector = function () {
try {
myProvider.providerInjector.get('myServiceProvider');//here is change in provider name
return "OK";
} catch (e) {
return e.toString();
}
};
According to angular docs the following is quoted for config and run blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants
can be injected into configuration blocks. This is to prevent
accidental instantiation of services before they have been fully
configured.
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be
injected into run blocks. This is to prevent further system
configuration during application run time.
This simply means, you cannot get instances of services inside config blocks.
I wrote this a while back, which explains the lifecycle of both injectors of AngularJS, i.e providerInjector and instanceInjector.
http://agiliq.com/blog/2017/04/angularjs-injectors-internals/

AngularJs can't inject $provide and $injector services in module.run

I'm trying to define services dynamically in angularjs, as the docs says, $provide and $injector are services, thus they should be injectable in module.run..
I need to make the dynamic services available from app bootstrap, that's why i'm trying to define them in module.run
angular.module('remote.interface',[])
.run(['$provide', '$injector', function(provide, injector){
// provide dynamically
}]);
but this ends up in an Error : [$injector:unpr] Unknown provider: $provideProvider <- $provide, and same eror for $injector if i try to remove $provide injection.
Where's the bug?
[EDIT]
after some research i tried something like this:
var module = angular.module('remote.interface',[])
.run([function(){
var provide = module.provider(),
injector = angular.injector();
provide.value('my.val',{i:'am a value'});
injector.get('my.val'); // this throws [$injector:unpr] Unknown provider: my.valProvider <- my.val
}]);
even if i remove the injector.get call, if i try to inject my.val, for example, in another-module's controller, angular throws the same error.
Have a look at the documentation for module and have a read at the comments in the example setup, particularly these comments.
config
You can only inject Providers (not instances) into config blocks
run
You can only inject instances (not Providers) into run blocks
Here is an example setup on JSFiddle injecting $provide and $injector correctly.
https://docs.angularjs.org/guide/module
angular.module('myModule', []).
config(function(injectables) { // provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
run(function(injectables) { // instance-injector
// This is an example of a run block.
// You can have as many of these as you want.
// You can only inject instances (not Providers)
// into run blocks
});

Resources