user2419560 user2419560 - 4 months ago 21
AngularJS Question

Angular getting unknown provider error when injecting service into controller

I'm working on a project that uses IIFE, a concept that I'm still beginning to grasp. My service seems to be fine, I'm using some Jasmine to determine that it is being defined, but when I try to inject it into my controller I get this error:

Unknown provider: StudentsServiceProvider <- StudentsService <- StudentsController


here is the controller in question:

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


And here is the service, just in case I messed up in there somehow:

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


All of the files listed above are included in the index.html. If I take out the references to StudentsService, I get no errors and all of the files get instantiated correctly.

Answer

Since the service StudentsService is in another module, you have to inject the 'ngInterview.api.students' module in the main module, as below:

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