如何在ui-router解析中访问服务?

时间:2015-01-20 13:59:42

标签: angularjs angular-ui-router

我有一个Angular Application app.js:

var app;

app = angular.module('app',
    [
        'exam',
        'ui.router'
    ])
    .controller('appController', AppController)
    .service('examService', ExamService));

我有一个配置文件:

var stateConfig = [
    '$locationProvider',
    '$sceDelegateProvider',
    '$sceProvider',
    '$stateProvider',
    'examService',
    function ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider, examService) {
        $locationProvider.html5Mode(true);
        $sceProvider.enabled(false);

        var exams = {
            name: 'exams',
            url: '/Exams',
            templateUrl: 'app/exams/partials/home.html',
            resolve: {
                exams: examService.getAdminExams()
            }
        };

    $stateProvider.state(exams);
}];

app.config(stateConfig);

有人可以给我一些建议。

当我跑步时,它告诉我:

 Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: 
[$injector:unpr] 
Unknown provider: examService
http://errors.angularjs.org/1.3.7/$injector/unpr?p0=examService

我检查过我的examService在其他两个文件之前声明:

<script src="/app/appController.js"></script>
<script src="/app/services/ExamService.js"></script>
<script src="/app/app.js"></script>
<script src="/app/appConfig.js"></script>
<script src="/app/appRun.js"></script>

同样在我的控制器中,我使用了examService,它没有任何问题。

这是我的控制器的样子:

var AppController = (function () {
    function AppController($scope, $state, es) {
        var _this = this;
        this.$scope = $scope;
        this.$state = $state;
        this.es = es;

    }
    AppController.$inject = [
        '$scope',
        '$state',
        'examService'
    ];
    return AppController;
})();

1 个答案:

答案 0 :(得分:4)

您只能将提供商注入config块。尝试注入$injector并使用它来获取examService

var stateConfig = [
    '$locationProvider',
    '$sceDelegateProvider',
    '$sceProvider',
    '$stateProvider',
    '$injector',
    function ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider, $injector) {
        $locationProvider.html5Mode(true);
        $sceProvider.enabled(false);

        var exams = {
            name: 'exams',
            url: '/Exams',
            templateUrl: 'app/exams/partials/home.html',
            resolve: {
                exams: function() {
                   //retrieve your service
                   var examService = $injector.get('examService');
                   return examService.getAdminExams()
                }
            }
        };

    $stateProvider.state(exams);
}];

或者根据docs,您可以像这样直接注入:

resolve: {
     exams: function(examService) {
        return examService.getAdminExams();
     }
}

如果您缩小脚本,这可能不起作用。试试这个:

resolve: {
    exams: ['examService',function(examService) {
         return examService.getAdminExams();
    }]
}