How do I call a service in angularJs config? - angularjs

I have a service that needs to be called in the app's config module but it errors when I try to inject it. Any ideas? FYI - this service works perfectly fine in controllers when injected and executed.
app.config(['$routeProvider', 'myService', function($routeProvider, myService) {
var controller = myService.getSomeValue() ? 'FirstController', 'SecondController';
$routeProvider
.when('/', {
'templateUrl': '/myTemplate.html'
'controller': controller
})
});
Failed to instantiate module app due to:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=myService

The AngularJS framework operates in two phases, the config phase and the run phase. Only provider objects can be injected in the config phase. Services can only be injected during the run phase.
From the Docs:
module.config(configFn);
Use this method to configure services by injecting their providers, e.g. for adding routes to the $routeProvider.
Note that you can only inject providers and constants into this function.
For more about how to configure services, see Provider Recipe.
For more information, see
AngularJS module type API Reference - config
AngularJS Developer Guide - Providers - Summary

Related

Difference between app.register.controller and app.controller in AngularJS

I don't know when to use app.register.controller and app.controller to create controller after module is created. I have googled but I didn't find clear difference between two scenarios. please post sample example.
Simple Answer
You can use app.controller to register providers before the app run (i.e., before bootstrap or ng-app, at config time). And app.register.controller is used to register a new provider when the app has already been bootstrapped (i.e., it's running).
A More Elaborated Explanation
AngularJs loads all providers that were registered before the module gets bootstrapped, once your module gets bootstrapped, angular won't look for registered providers anymore. It's fine for most apps, but, in some cases, you will have to load new providers at run time (i.e., after the app gets bootstrapped), that's called lazy loading. Therefore, provided that angular won't look for registered components anymore, you will have too register it manually.
For example:
var app = angular.module('myApp', []);
app.controller('myController1', function (){});
angular.element(documento).ready(function () {
// equivalent to ng-app attribute
angular.bootstrap(document, ['myApp']);
});
At this point, angularjs will load all providers registered before the bootstrap phase. However, if you try to register a controller again, it won't get loaded on your application, because angularjs loads it just when bootstrapping the app.
So, to register a provider at run time, you have to expose the angularjs' provider and component factories on your module like so:
app.config(function($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.register = {
component: $compileProvider.component,
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
});
Check this answer for more info: https://stackoverflow.com/a/20922872/4488121
Finally, now it allow you to register a provider after the app bootstrap (i.e., at run time).
app.register.controller('myController2', function (){});

$urlProvider not resolvable in controller

I can inject $urlProvider in module.config() but when i try to do it in module.controller() I am getting this error:
Unknown provider: $urlRouterProviderProvider <- $urlRouterProvider <- MyCtrl
I have included angular-ui, also imported ui.router in the module.
I cannot see anybody doing this online, but why should it not work?
Providers are meant to be configured in the config phase, and then they can be injected into a controller, or the run phase, sans the Provider post-fix:
app.config(function($urlRouterProvider) {
$urlRouterProvider.deferIntercept();
});
app.run('MyCtrl', function($urlRouter) { // no Provider post-fix
$urlRouter.listen();
});
See the Angular docs on Providers and the UI-Router's guide on $urlRouterProvider for more information.

Restangular: Error: Unknown provider

I want to inject Restangular in my app to communicate with via REST.
So, here I am know with an error:
Error: [$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- Api
Api is my own module here. What I'm doing:
Creating a main module called Dashboard
Creating a submodule called API
Now I want to use Restangular, but couldn't figure out how Angular is managing the dependencies...
Here is my sub-module where I inject Restangular:
angular.module( 'dashboard.api', ['restangular']).factory('Api', ['$http', 'Config', 'Restangular', function($http, Config, Restangular) {
My main module, Dashboard, doesn't need to inject Restangular, right?
angular.module( 'dashboard', [ 'dashboard.api'])
How is the injection-depency working within submodules? How can I
integrate Restangular in my app?
EDIT: Source file is included:
Okay I found the problem and the solution.
You have to differ between restangular(the module) and Restangular the service.
First, you have to include the main module of restangular into your app:
For me, it was this (polygon is a submodule of my app:
angular.module('polygons', ['restangular']);
Then, I wanted to inject restangular into a factory of that submodule:
angular.module('polygons').factory('polygonService', ['Restangular', polygonService]);
function polygonService(Restangular) {
// ...
});
This works for me. Hope this helps.

Is automatic dependency injection available in AngularJS?

I want to automatically dependency inject an Angular built-in service into all services within an Angular module / app.
The service I want to inject is ... $exceptionHandler
I do not want $exceptionHandler to be global ... e.g. I do not want to do ...
window.$exceptionHandler = $exceptionHandler
But I also do not want to dependency inject $exceptionHandler into every service manually using ...
angular.module('myApp').factory('myService', ['$exceptionHandler', function ($exceptionHandler) {
Is it possible to automatically inject an Angular built-in service into all services within an Angular module / app ?
Many thanks
It can be made more convenient through nested modules. In the root (or global) module inject $exceptionHandler and all the other modules you create or want to use. All sub modules of the root module will have $exceptionHandler injected without further ado. You still have to name the $exceptionHandler in your controller and factory function definitions, though, so it is not possible to completely get rid of injection artefacts.
Example:
app.js
angular.module('app', ['ionic', '$exceptionHandler', 'ngCordova','app.home',
'app.impressum'])
.run(function ($ionicPlatform, $state) {
..
})
.config(function ($stateProvider, $urlRouterProvider, $provide, $exceptionHandler, $ionicConfigProvider, $compileProvider) {
$stateProvider
.state('app', {
...
})
}
);
Now the app.home-Module:
home.js
angular.module('app.home', ['app.home.controller', 'app.home.factory']);
home/controller.js
angular.module('app.home.controller', [])
.controller('homeController', function ($scope, $exceptionHandler) {
...
});
app.home.factory and the three modules for app.impressum are quite similar, so I leave that to you.
As you can see you still have to put $exceptionHandler into the function parameters of your controller, but no injection is required on the module itself, because it inherits all injections from it's parent modules app.home and app.
By using a hierarchy of modules in an AngularJS app injections can be made where due... more globally for the whole app, for module groups or only on single modules. Plus we get a very clean structure for the App's sections.

injecting service into angularjs app config

I am trying to inject $http serivce into app config, but getting "unknown provider $http error".
woi.config(['$routeProvider', '$locationProvider','$http', function($routeProvider, $locationProvider,$http){
$routeProvider
.when("/channels", {
templateUrl: test,
resolve: {
app: function($http){
}
}
})
]});
My question is , is it possible to inject $http serivce in app config ,and if not then what are the other ways to do ajax call before controller and template is called.
Thanks,
You can directly pass $http or any dependency into the function, without defining it at config function. The DI framework of Angular would inject dependencies for resolve object functions.

Resources