【问题标题】:How to inject a service into app.config in AngularJS如何在 AngularJS 中将服务注入 app.config
【发布时间】:2014-03-27 09:07:05
【问题描述】:
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
  })

authService.getLoggedin() 根据用户是否登录返回 false 或 true。如果不允许,我想不允许他们访问 URL。

但我收到此错误: 错误:[$injector:modulerr] 无法实例化模块 wikiApp,原因如下: [$injector:unpr] 未知提供者:authService

【问题讨论】:

    标签: angularjs service config


    【解决方案1】:
    1. angular.config 只接受提供者
    2. 每个服务、工厂等都是 Provider 的实例

    因此,要在配置中注入服务,您只需在服务的名称中添加“Provider”即可调用该服务的提供者。

    angular.module('myApp')
      .service('FooService', function(){
        //...etc
      })
      .config(function(FooServiceProvider){
        //...etc
      });
    

    【讨论】:

    • 只是一个额外的信息。您可以按如下方式使用 FooService: FooServiceProvider.$get.NameOfFunctionInService(perimeters if applicable)
    • 只是想强调我必须使用$get(),因为这是一个函数:FooServiceProvider.$get().NameOfFunctionInService(perimeters if applicable)。不确定是否发生了变化,或者这是一个错字。无论如何,谢谢你们!
    【解决方案2】:

    在配置阶段,您只能请求提供者($routeProvider、$locationProvider 等),这意味着您不能注入任何其他实例,因此我建议您在运行阶段注入您的服务,在那里您将拥有您的服务实例。

    // 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...
      }); 
    });
    

    【讨论】:

    • 选中此link 以将您的服务设置为自定义提供程序。
    【解决方案3】:

    如果您想在路由 (.config) 中调用外部函数(在您的情况下为 Service 函数),如下所示:templateProvider.getTemplate('about')

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

    您不能为此创建服务或工厂。相反,您必须创建一个 Provider。

    这是一个真实的 Provider 示例,它根据名称生成模板路径:

    (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';  
            }  
    
        };  
    })();  
    

    此类Provider在路由(.config)中的用法如下:

    (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');  
        };  
    })();  
    

    贵宾注意事项:

    要注入提供程序,您必须使用 xxxProvider 对其进行后缀(提供程序的名称不应后缀,仅在 .config 中注入时)。

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 1970-01-01
      • 2014-01-27
      • 2016-12-09
      • 2014-02-08
      • 2013-01-24
      • 1970-01-01
      • 2013-08-30
      • 2013-03-02
      相关资源
      最近更新 更多