AngularJS - 从其他模块注入服务时出错

时间:2014-12-24 06:17:48

标签: angularjs

我是AngularJs的新手,我无法完全弄清楚下面的问题。

在下面的示例中,有2个服务MongoRESTService&模块MongoRESTService2中定义了common-services

主模块olive取决于common-services,主控制器尝试调用上述2个服务中的函数。

虽然我能够成功调用函数MongoRESTService.get(),但MongoRESTService.queryMongoData()会抛出错误。

错误消息

  

angular.js:10126 Error: [$injector:unpr] http://errors.angularjs.org/1.2.28/$injector/unpr?p0=MongoRESTService2Provider%20%3C-%20MongoRESTService2

     

Unknown provider: MongoRESTService2Provider <- MongoRESTService2

代码

// services.js

var oliveModule = angular.module('common-services')

oliveModule.service('MongoRESTService', function($http, $q, $scope) {

   this.get = function(path){
      ...
   };
});

oliveModule.service('MongoRESTService2', function($scope, MongoRESTService) {
    this.queryMongoData = function (){
        MongoRESTService.get('/clients').then(function(data){
            $scope.clients = ...;
        });
    };
});


// main.js
var oliveModule = angular.module('olive', ['common-services']);

oliveModule .controller('MainController',
    function($scope, $http, MongoRESTService, MongoRESTService2) {
        //this line works
        MongoRESTService.get('/clients').then(function(data){
            ...
        })

        //this throws error
        MongoRESTService2.queryMongoData();
    }
);

1 个答案:

答案 0 :(得分:4)

正如错误所述,

所以试试

oliveModule.service('MongoRESTService2',['$scope','MongoRESTService',function($scope, MongoRESTService) {
    this.queryMongoData = function (){
        MongoRESTService.get('/clients').then(function(data){
            $scope.clients = ...;
        });
    };
}]);
相关问题