将服务注入控制器时,Angular会收到未知的提供程序错误

时间:2016-08-02 01:56:40

标签: angularjs dependency-injection controller iife

我正在开发一个使用IIFE的项目,这个概念我仍然开始掌握。我的服务似乎很好,我使用一些Jasmine来确定它是否被定义,但是当我尝试将它注入我的控制器时,我得到了这个错误:

Unknown provider: StudentsServiceProvider <- StudentsService <- StudentsController

这是有问题的控制器:

(function() {
    'use strict';

    angular
        .module('ngInterview.students')
        .controller('StudentsController', StudentsController);

    StudentsController.$inject = ['StudentsService'];
    function StudentsController(StudentsService) {

        /**
         * Model
         */

        var vm = this;

        /**
         * Initialization
         */

        activate();

        /**
         * Implementations
         */

        function activate() {
            // Initialization code goes here
            vm.students = StudentsService.getStudents();
        }
    }
})();

这是服务,以防我以某种方式搞砸了:

(function() {
    'use strict';

    angular
        .module('ngInterview.api.students')
        .service('StudentsService', StudentsService);

    StudentsService.$inject = ['$http'];
    function StudentsService($http) {

        /**
         * Exposed functions
         */

        this.getName = getName; // This function serves no purpose. It's just here as an example.

        this.getStudents = function() {
            return $http({
                url: "CUSTOM_URL_HERE",
                method: "GET"
            }).then(function successCallback(res) {
                return res;
            }, function errorCallback(res) {
                return this.getStudents();
            });
        }

        /**
         * Implementations
         */

        function getName() {
            return 'studentsService';
        }
    }
})();

上面列出的所有文件都包含在index.html中。如果我取出对StudentsService的引用,我没有错误,所有文件都被正确实例化。

1 个答案:

答案 0 :(得分:1)

由于服务StudentsService位于另一个module,您必须在主'ngInterview.api.students'中注入module module,如下所示:

angular
  .module('ngInterview.students', ['ngInterview.api.students'])