如何注入一个服务到AngularJS的app.config [英] How to inject a service into app.config in AngularJS

查看:958
本文介绍了如何注入一个服务到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()返回取决于如果用户或没有登录无论或真或假。然后,我想不会让他们的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.

但是我得到这个错误:
错误:[$喷油器:modulerr]未能实例化模块wikiApp由于:
[$喷油器: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天全站免登陆