How to inject a service into app.config in Angular

2019-01-17 17:51发布

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

3条回答
神经病院院长
2楼-- · 2019-01-17 18:25
  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
  });
查看更多
▲ chillily
3楼-- · 2019-01-17 18:45

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...
  }); 
});
查看更多
一夜七次
4楼-- · 2019-01-17 18:49

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).

查看更多
登录 后发表回答