我有以下组件,我试图在其中注入(inject)服务:
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!!!!!!!!');
});
}
]
});
该服务如下所示:
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
};
});
我的phone-list.module.js看起来像这样:
angular.module('phonecatApp', [
'phoneList',
'authentication',
]);
angular.module('phoneList', ['authentication']);
当我运行这个时,我收到错误:
Uncaught ReferenceError: authenticationService is not defined
当我将“authenticationService”放入“”中时,出现错误:
Error [$injector:unpr] authtenticationService
最佳答案
服务似乎没有正确注入(inject)到 PhoneListController 中。
将其更改为:
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
...
数组中的字符串只是为了保证注入(inject)的依赖引用缩小的安全。该服务仍需要作为函数参数添加。
另外请务必为每个组件调用 angular.module
一次:
app.module.js
angular.module('phonecatApp', [
'ngRoute',
'phoneList',
'authentication',
]);
电话列表.module.js
angular.module('phoneList', ['authentication']);
关于javascript - Angular 未捕获引用错误: Service is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39440866/