如何在 AngularJS 中将服务注入 app.config [英] How to inject a service into app.config in AngularJS

查看:27
本文介绍了如何在 AngularJS 中将服务注入 app.config的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

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.

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

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

推荐答案

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

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

这篇关于如何在 AngularJS 中将服务注入 app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆