Jim Wharton
Jim Wharton

Reputation: 1415

AngularJS inject service into multiple controllers

I have defined a service in its own module:

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;
  });

In another module, (in another file) I have a controller where I'd like to use it:

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);
    });

]);

I have an init for this module in a file called init.js that includes the dependency like this:

'use strict';

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

It doesn't look like it's actually injecting the foteDatasetsService INTO the controller though. If I run the app, I get an error:

Cannot call method 'getDatasets' of undefined

So if I force the issue by including the foteDatasetsService in in the controller like this:

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

it gives me this error:

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

EDIT: I want to be able to inject this service into 3 controllers that will need to get this same info.

Any ideas why the factory is not creating the provider? I'm lost on that one...

Upvotes: 4

Views: 12588

Answers (1)

artur grzesiak
artur grzesiak

Reputation: 20348

Instead of this:

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

Try this:

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

You already have injected the foteDatasetsService, now you just want to inject the service foteAPIservice.

UPDATE as @dtabuenc remarked it would be better not to append Service in a module name.

Upvotes: 8

Related Questions