Resolving dependency for $state.go in Angular UI Router - javascript

I have a provider config which uses $state.go to jump to states. When I use $state as a function parameter it works, but when I try to modify the function parameters to support minification such as
.provider('Navigation',["$stateProvider","$state",function($stateProvider,$state)
then I get the following resolve dependency error :
Uncaught Error: [$injector:modulerr] Failed to instantiate module apfPrototypeJs due to:
Error: [$injector:unpr] Unknown provider: $state
How to circumvent this problem?

You can only inject providers in a provider because no services are instantiated at that point yet and also because the provider methods are used especially for configuration, they can only be accessed during the config phase of the app, it does not make sense to have the ability to inject any services. But You can inject any service (not provider) in the provider's constructor function defined via $get property.
i.e
.provider('Navigation',["$stateProvider",function($stateProvider) { //Inject provider here
this.$get = ["$state", function($state){ //Inject $state here
console.log($state)
}]
}]);
As an alternate syntax (using $inject to support minification) you could do:-
.provider('Navigation', function(){
this.$get = navigationService;
navigationService.$inject = ['$state'];
function navigationService($state) {
console.log($state)
}
}]);

Related

Angular dependency injection in $resource factory

A doubt about DI on factory resource:
AFAIK the below sample is the recommended way to inject dependencies in Angular1:
angular.module('myApp').factory('Resource', Resource);
Resource.$inject = ['$resource', 'CONSTANTS'];
function Resource($resource, CONSTANTS) {
return $resource(CONSTANTS.server_url + '/resource/:id');
}
But I'm having problems in use it combined with the new keyword in my Controller:
var resource = new Resource();
This results in an error saying that CONSTANTS is undefined. Using the below syntax, it works normally.
angular.module('myApp').factory('Resource', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
return $resource(CONSTANTS.server_url + '/resource/:id');
}]);
Why this happens?
Angular's injections system only works if you're using Angular's injection system. By doing new Resource(), you're instantiating a plain Javascript "class" yourself using plain Javascript; the $inject property on Resource doesn't magically do anything in this case.
What you're doing with module(..).factory('Resource', ..) is to define 'Resource' as an injectable dependency. You must now use this as a dependency for your controller, and Angular will work its injection system:
module(..).controller('MyController', ['Resource', function (Resource) {
Resource.get(...)
}]);

Call to a function within $get of Provider modules causes TypeError

This is my provider.
App.provider('cloudinaryDetails', function(CloudinaryProvider){
function setCloudinaryDetails(cloudinaryDetails){
CloudinaryProvider.configure({
cloud_name: cloudinaryDetails.cloud_name,
api_key: cloudinaryDetails.api_key
});
}
this.$get = function($http){
return {
initialize: function(){
return $http.get('path/to/api').then(function(response){
setCloudinaryDetails(response.data);
});
}
};
};
});
I am calling the initialize function in config module
App.config(function(cloudinaryDetailsProvider){
cloudinaryDetailsProvider.initialize();
});
Console Error:
[$injector:modulerr] Failed to instantiate module App due to:
TypeError: cloudinaryDetailsProvider.initialize is not a function
Cause:
You are injecting the cloudinaryDetailsProvider "provider" but initialize is not defined on the provider, it is defined on the instance.
Suggested Fix:
To get a reference to the cloudinaryDetails "instance", create a run block and inject the instance instead of the provider.
App.run(function(cloudinaryDetails){
cloudinaryDetails.initialize();
});
See AngularJS docs for an explanation on how providers work

Dynamically injecting a specific factory based on route parameter fails for some reason

I want to dynamically inject a factory into my Angular controller based on the route parameter. This is my route configuration:
$routeProvider
.when("/tables/:table",
{
controller: "tableController",
templateUrl: "/app/views/table.html",
resolve: {
"factory": function r($route) {
return $injector.get($route.current.params.table + "Factory"); // Error!
}
}
})
For instance, when the route is tables/employee, I want an employeeFactory to be injected into tableController, and so on.
Unfortunately, this configuration does not work — I am getting an Unknown provider: employeeFactory error in the r function.
On the other hand, I can instead pass an $injector service directly to the tableController and successfully resolve employeeFactory there:
(function (angular) {
var tableController = function ($routeParams, $injector) {
// employeeFactory resolves successfully here!
var factory = $injector.get($routeParams.table + "Factory");
};
angular.module("appModule").controller("tableController", tableController);
})(angular);
However, I do not like this approach because it follows the service locator anti-pattern. I would really like factory to be injected using routing configuration and not this ugly workaround.
So, why Angular is throwing an error when using $injector.get() with resolve, but successfully resolves the factory inside of the tableController? I am using Angular 1.4.4.
You apparently use $injector that was injected into config block, and it differs from $injector that is injected anywhere else. The former acts on service providers, the latter acts on service instances.
It should be
"factory": function r($route, $injector) {
return $injector.get($route.current.params.table + "Factory");
}

How do I know what dependencies I can inject into a controller?

I am trying to use $routeProvider dependency inside my controller:
.controller('mainController', function($scope, $state, $routeProvider) {
But I am getting the error:
Error: [$injector:unpr] Unknown provider: $routeProviderProvider <- $routeProvider
How do I know what dependencies I can inject into any given controller?
There are two phases inside angular
Configuration Phase (Here we use app.config to write a code)
Run phase (Where we use app.run, after run cycle all other directives gets executed using compile cycle)
Provider is nothing but service/factory but the most important thing is it can be accessible inside configuration phase.
Example
Suppose we have below provider
myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
var useTinfoilShielding = false;
this.useTinfoilShielding = function(value) {
useTinfoilShielding = !!value;
};
this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {
return new UnicornLauncher(apiToken, useTinfoilShielding);
}];
});
While inject it inside config you should always prefix it Provider like unicornLauncherProvider
While using it inside controller you could use it as unicornLauncher
Note:
Provider are always accessible inside .config(configuration)
phase with suffix Provider in their name, While inside controller you could > directly inject it using unicornLauncher (direct provider name)
Services/Factory They are not visible in config phase of angular
Still confuse then do refer this link
You can only access services in the controller not the providers so use $route here.
Therefore you are getting error $routeProviderProvider becuase it is looking for the provider for $routeProvider which is itself a provider for $route.
Docs

Dependency errors in Angular when creating an $http interceptor as a standalone module

Here is a working example of how I have set up an interceptor which attaches an authentication token to each request (this is more or less the example from https://docs.angularjs.org/api/ng/service/$http)
angular.module("app", [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push("authInterceptor");
})
.factory("authInterceptor", function ($q) {
return {
// interceptor configuration here
}
})
I have a lot of other stuff in my config and run blocks which call and initiate services from different angular modules, so I want to tidy things up a bit. However I understand there are some very specific rules to dependency injection in config blocks, which I don't quite understand, and these are preventing me from defining my authInterceptor factory in a separate module. As other logic in the config and run blocks calls other modules in the app, declaring that interceptor right there looks out of place.
This is what I want to do:
angular.module("services.authInterceptor", [])
.factory("authInterceptor", function ($q) {
return {
// interceptor configuration here
}
});
angular.module("app", [
"services.authInterceptor"
]).config(function ($httpProvider, authInterceptor) {
$httpProvider.interceptors.push("authInterceptor");
});
// Error: Unknown provider authInterceptor.
I tried injecting it to the run block instead, but I guess you're not allowed to inject $httpProvider there:
angular.module("app", [
"services.authInterceptor"
]).run(function ($httpProvider, authInterceptor) {
$httpProvider.interceptors.push("authInterceptor");
});
// Error: Unknown provider: $httpProviderProvider <- $httpProvider
Where should I inject the module so that $httpProvider is also injectable, and where should I add the interceptor to existing ones? My main goal is keeping the interceptor and other similar services in their own self-containing modules.
EDIT
I get a different error which seems to be getting me closer when I declare a provider instead of factory (for some reason I always thought these were interchangeable):
angular.module("services.authInterceptor")
.provider("authInterceptor", function ($q) {
return {}
})
// Error: Unknown provider: $q
So it now successfully injects authInterceptor to my config block, but fails when trying to find $q.
During the configuration phase only providers and constants can be injected. This is to prevent instantiation of services before they have been fully configured.
This is why you register interceptors by name (pushing the name as a string into the $httpProvider.interceptors array). They will be resolved later during runtime.
This is exactly what you did in your working example, and what you need to do in your second, even when the interceptor is in another module:
angular.module("services.authInterceptor", [])
.factory("authInterceptor", function ($q) {
return {
// interceptor configuration here
}
});
angular.module("app", ["services.authInterceptor"])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
Demo: http://plnkr.co/edit/A8SgJ87GOBk6mpXsoFuZ?p=preview

Categories