问题
I have the following component in which I am trying to inject a service:
angular.
module('phoneList').
component('phoneList', {
templateUrl: '/static/common/angular/phone-list/phone-list.template.html',
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
var self = this;
authenticationService.authenticate().then(function(){
console.log('it worked!!!!!!!!');
});
}
]
});
The service looks like this:
angular.module('authentication').factory('authenticationService', function($http, $se){
function authenticate(){
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
console.log('auth service: '+data['access_token']);
$sessionStorage.access_token = data['access_token'];
});
}
function getToken(){
return $sessionStorage.access_token;
}
return {
authenticate:authenticate,
getToken:getToken
};
});
My phone-list.module.js looks like this:
angular.module('phonecatApp', [
'phoneList',
'authentication',
]);
angular.module('phoneList', ['authentication']);
When I run this i get the error:
Uncaught ReferenceError: authenticationService is not defined
When I put 'authenticationService' in '', I get the error:
Error [$injector:unpr] authtenticationService
回答1:
It seems the service isn't properly injected into the PhoneListController.
Change it to:
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
...
The strings in the array are just to keep the injected dependency references minification safe. The service still needs to be added as a function argument.
Also be sure to call angular.module
once for each component:
app.module.js
angular.module('phonecatApp', [
'ngRoute',
'phoneList',
'authentication',
]);
phone-list.module.js
angular.module('phoneList', ['authentication']);
来源:https://stackoverflow.com/questions/39440866/angular-uncaught-referenceerror-service-is-not-defined