2014-12-24 82 views
2

我是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(); 
    } 
); 

回答

4

正是因爲錯誤狀態,

所以儘量

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

如果你需要澄清,這被稱爲依賴注入的「數組符號」 .. https://docs.angularjs.org /導向/二 – yUdoDis