我正在使用angularjs开发应用程序,并希望存储一些会话变量。无法在angularjs中检索服务对象的属性
我对app.js代码是包含控制器,服务和工厂:以下JSON
(function(){
var app = angular.module('test', []);
app.controller('ApplicationController', function ($scope,
AuthService, Session) {
$scope.currentUser = null;
this.Session = Session;
console.log(Session);
console.log(Session.id);
$scope.isAuthenticated = AuthService.isAuthenticated;
if (!$scope.isAuthenticated()) {
AuthService.login();
}
});
app.service('Session', function() {
var session = {};
session.create = function(sessionId, userId, userRole) {
session.id = sessionId;
session.userLogin = userId;
session.userRole = userRole;
};
session.destroy = function() {
session.id = null;
session.userLogin = null;
session.userRole = null;
};
return session;
});
app.factory('AuthService', function ($http, Session) {
var authService = {};
authService.login = function() {
return $http
.get('authenticate.php')
.then(function (res) {
Session.create(res.data.session_id, res.data.login, res.data.role_id);
});
};
authService.isAuthenticated = function() {
return !!Session.id;
}
return authService;
});
})();
authenticate.php可以包含例如:
{"session_id":"076d89db-141a-11e5-8e8f-18a9059996df","login":"test","role_id":"2","error":null}
的问题是,我不能检索会话变量(Session
对象的字段),即使它们已设置。在控制器初始化期间,我打印Session
变量,它包含所有字段 - id
,userName
,userRole
,但是当我打印Session.id
时,我得到未定义的值。
如何访问这些字段?
感谢,兹比涅克
谢谢,我已经尝试过了,但至今没有运气。我编辑了帖子,所以现在它包含完整的app.js文件和json,工厂预期 – Zbynek