我在项目中正确注入一堆模块时遇到了麻烦。这是我正在关注的项目
https://thinkster.io/django-angularjs-tutorial
当我尝试制作一个新帖子时 - 角度抛出以下错误
Error: Authentication.getAuthenticatedAccount(...) is undefined
submit@http://localhost:8000/static/javascripts/posts/controllers/new-post.controller.js:31:21
$parseFunctionCall@http://localhost:8000/static/bower_components/angular/angular.js:12474:15
这就是问题似乎发生的地方
function NewPostController($rootScope, $scope, Authentication, Snackbar, Posts) {
var vm = this;
vm.submit = submit;
function submit() {
$rootScope.$broadcast('post.created', {
content: vm.content,
author: {
username: Authentication.getAuthenticatedAccount().username
}
});
$scope.closeThisDialog();
Posts.create(vm.content).then(createPostSuccessFn, createPostErrorFn);
function createPostSuccessFn(data, status, headers, config) {
Snackbar.show('Success! Post created.');
}
function createPostErrorFn(data, status, headers, config) {
$rootScope.$broadcast('post.created.error');
Snackbar.error(data.error);
}
}
}
但是我可以看到代码中正在使用正确的模块。
这是我的new-post.controller.js文件,其中我注入了身份验证依赖项
angular
.module('thinkster.posts.controllers')
.controller('NewPostController', NewPostController);
NewPostController.$inject = ['$rootScope', '$scope', 'Authentication', 'Snackbar', 'Posts'];
这是我的posts.module.js文件片段
angular
.module('thinkster.posts', [
'thinkster.posts.controllers',
'thinkster.posts.directives',
'thinkster.posts.services'
]);
angular
.module('thinkster.posts.controllers', []);
这是身份验证服务模块的片段
angular
.module('thinkster.authentication.services')
.factory('Authentication',Authentication);
Authentication.$inject = ['$cookies','$http'];
function Authentication($cookies,$http){
var Authentication = {
getAuthenticatedAccount: getAuthenticatedAccount,
isAuthenticated: isAuthenticated,
register:register,
login : login,
logout:logout,
setAuthenticatedAccount: setAuthenticatedAccount,
unAuthenticate: unAuthenticate
};
return Authentication;
function getAuthenticatedAccount(){
if (!$cookies.authenticatedAccount){
return;
}
return JSON.parse($cookies.authenticatedAccount);
}
验证模块的片段
angular
.module('thinkster.authentication',[
'thinkster.authentication.controllers',
'thinkster.authentication.services'
]);
- 最后,下面的thinkster模块
angular
.module('thinkster', [
'thinkster.config',
'thinkster.routes',
'thinkster.authentication',
'thinkster.layout',
'thinkster.posts',
'thinkster.utils'
]);
认证服务工作正常,因为我能够登录和注销项目。我错误地找错了地方吗?
答案 0 :(得分:0)
代码片段缺少NewPostController定义。在没有看到该代码的情况下,我猜想可能不会将Authentication对象传递给函数。
function NewPostController($rootScope, $scope, Authentication, Snackbar, Posts) {
}
您可以使用NewPostController中的以下代码查看Authentication对象上可用的方法:
for (var key in Authentication) {
console.log(typeof Authentication[key], key);
}
如果对象有效,你应该看到“function getAuthenticatedAccount”。