AngularJS将服务注入多个控制器

时间:2013-11-29 20:48:44

标签: angularjs dependency-injection

我已在自己的模块中定义了一项服务:

angular.module('foteDatasetsService', [])
  .factory('foteAPIservice', function($http) {

    var foteAPI = {};

    foteAPI.getDatasets = function() {
      return $http({
        method: 'JSONP',
        url: 'http://localhost:8080/datasets?callback=JSON_CALLBACK'
      });
    }

    return foteAPI;
  });

在另一个模块中,(在另一个文件中)我有一个控制器,我想用它:

angular.module('foteRequests').controller('foteRequestsController',
  ['$scope', function foteRequestsController($scope, foteAPIservice) {

    //snip other stuff

    $scope.datasets = [];

    foteAPIservice.getDatasets().success(function (response) {
      //Digging into the response to get the relevant data
      $scope.datasets = response;
      console.log(response);
    });

]);

我在一个名为 init .js的文件中有一个init模块,它包含这样的依赖项:

'use strict';

angular.module('foteRequests', ['foteDatasetsService']);

它看起来并不像实际上将foteDatasetsService注入控制器。如果我运行应用程序,我会收到错误:

Cannot call method 'getDatasets' of undefined

所以,如果我通过将foteDatasetsService包含在控制器中来强制解决问题:

angular.module('foteRequests').controller('foteRequestsController', ['$scope',
'foteDatasetsService', function foteRequestsController($scope, foteAPIservice) {
...
}]);

它给了我这个错误:

Error: [$injector:unpr] Unknown provider: foteDatasetsServiceProvider <- foteDatasetsService

编辑:我希望能够将此服务注入3个需要获取相同信息的控制器。

为什么工厂没有创建提供商的任何想法?我迷失在那一个......

1 个答案:

答案 0 :(得分:8)

而不是:

angular.module('foteRequests').controller('foteRequestsController',
['$scope', 'foteDatasetsService', function foteRequestsController($scope, foteAPIservice)
{ ... }]);

试试这个:

angular.module('foteRequests').controller('foteRequestsController',
['$scope', 'foteAPIservice', function foteRequestsController($scope, foteAPIservice)
{ ... }]);

您已经injected foteDatasetsService,现在您只想inject服务foteAPIservice

更新,因为@dtabuenc评论说最好不要在Service名称中附加module