Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a service into app.config in AngularJS

wikiApp.config(['$routeProvider','authService', 
  function($routeProvider,authService) {
var admin = authService.getLoggedin();

$routeProvider
    .when('/hjem',{
        templateUrl: 'partials/homeContent.html',
    admin: false
    })
  .when('/articles/:article',{
    templateUrl: 'partials/articles.html',
    admin: false
  })
  .when('/newArticle',{
    templateUrl: 'partials/postArticle.html',
    controller: 'articleController',
    admin: true
  })

The authService.getLoggedin() returns either false or true depending on if the user is logged in or not. Then i would like to not allow them to the Url if they are not allowed.

But i get this error: Error: [$injector:modulerr] Failed to instantiate module wikiApp due to: [$injector:unpr] Unknown provider: authService

like image 560
user2925894 Avatar asked Mar 27 '14 09:03

user2925894


People also ask

How do you inject service in AngularJS?

There is one more way to inject dependencies in AngularJS: by using the $inject service. In doing so, we manually inject the dependencies. We can inject $scope object dependencies using the $inject service as shown in the listing below: function ProductController($scope){ $scope.

What is injector service in AngularJS?

Overview. $injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.

When you inject a service into a controller?

When a service or controller needs a value injected from the factory, it creates the value on demand. It normally uses a factory function to calculate and return the value. Let's take an example that defines a factory on a module, and a controller which gets the factory created value injected: var myModule = angular.


3 Answers

  1. angular.config only accepts Providers
  2. every service, factory etc are instances of Provider

So to inject a service in config you just need to call the Provider of the service by adding 'Provider' to it's name.

angular.module('myApp')
  .service('FooService', function(){
    //...etc
  })
  .config(function(FooServiceProvider){
    //...etc
  });
like image 68
vilsbole Avatar answered Oct 11 '22 01:10

vilsbole


During the configuration phase you can only ask for providers ($routeProvider, $locationProvider etc.) it means you cannot inject any other instance, so I would suggest injecting your service in the run phase, there your will have an instance of your service.

// configuration
app.config(function($routeProvider) {

});

//inject any instance 
 app.run(function($rootScope,authService) {
  var admin = authService.getLoggedin();

  $rootScope.$on('$routeChangeStart', function(next, current) { 
     // your logic here...
  }); 
});
like image 37
Alex Choroshin Avatar answered Oct 11 '22 02:10

Alex Choroshin


If you want to call an external function (in your case Service function) form your routes (.config) as shown below: templateProvider.getTemplate('about')

.state('index.about', {  

    url: "/about",  
    templateUrl: templateProvider.getTemplate('about'),  
    controller: 'AboutCtrl',  
    controllerAs: 'about',  
    data: {pageTitle: 'About Us Page'}  

})  

you cannot create a Service or Factory for that. Instead you must create a Provider.

Here’s a real example of a Provider that generates the template path from the name:

(function () {  

    'use strict';  
    angular  

        .module('mega-app')  

        .provider('template', provider);  

      function provider(CONSTANT) {  

        // The provider must include a $get() method This $get() method  
        // will be invoked using $injector.invoke() and can therefore use  
        // dependency-injection.  
       this.$get = function () {  

            return {}  

        };  
       /**  
         * generates template path from it's name  
         *  
         * @param name  
         * @returns {string}  
         */  
       this.getTemplate = function (name) {  

            return CONSTANT.TEMPLATES_URL + name + '/' + name + '.html';  
        }  


        /**  
         * generates component path from it's name  
         * @param name  
         * @returns {string}  
         */  
       this.getComponent = function (name) {  

            return CONSTANT.COMPONENTS_URL + name + '.html';  
        }  

    };  
})();  

The usage of such Provider in the routes (.config) will be as follow:

(function () {  

    'use strict';  
    angular  

        .module('mega-app')  

        .config(routes);  
   function routes($stateProvider, $urlRouterProvider, templateProvider) {  



       $stateProvider  
            //----------------------------------------------------------------  
            // First State  
            //----------------------------------------------------------------  
            .state('index', {  

                abstract: true,  
                url: "/index",  
                templateUrl: templateProvider.getComponent('content'),  
                controller: 'IndexCtrl',  
                controllerAs: 'index',  
            })  

            //----------------------------------------------------------------  
            // State  
            //----------------------------------------------------------------  
            .state('index.home', {  

                url: "/home",  
                templateUrl: templateProvider.getTemplate('home'),  
                controller: 'HomeCtrl',  
                controllerAs: 'home',  
                data: {pageTitle: 'Home Page'}  

            })  

            //----------------------------------------------------------------  
            // State  
            //----------------------------------------------------------------  
            .state('index.about', {  

                url: "/about",  
                templateUrl: templateProvider.getTemplate('about'),  
                controller: 'AboutCtrl',  
                controllerAs: 'about',  
                data: {pageTitle: 'About Us Page'}  

            })  

        //----------------------------------------------------------------  
        // Default State  
        //----------------------------------------------------------------  
       $urlRouterProvider.otherwise('/index/home');  
    };  
})();  

VIP Note:

to inject the provider you must postfix it with xxxProvider (that name of the provider should not be postfixed, only on injection in the .config).

like image 29
Mahmoud Zalt Avatar answered Oct 11 '22 00:10

Mahmoud Zalt