大家好! 我正在创建具有授权的应用程序。 要在会话期间存储用户数据,我使用此类服务:
app.service('Session', function ($rootScope, $cookies) {
var Session = $rootScope.$new();
Session.createSession = function (accessTo, level, user_data) {
this.level = level;
this.accessTo = accessTo;
if(user_data) {
$cookies.isAuth = true;
} else {
$cookies.isAuth = false;
}
this.user = {
email : user_data.email,
fullname : user_data.fullname,
id : user_data.id,
level : user_data.level
}
if(accessTo && accessTo.length == 1 && !$cookies.account) {
this.account = accessTo[0].id;
$cookies.account = accessTo[0].id;
} else {
this.account = $cookies.account;
}
};
Session.destroy = function () {
this.level = null;
this.account = null;
this.user = null;
this.isAuth = false;
$cookies.account = null;
};
return Session;
});
在控制器使用中:
Session.createSession(some, params, here);
后来它把一些数据放到了rootcope中,我可以在控制台中显示它,但是当我试图查看例如Session.user / .level等时,它不起作用。怎么了?
答案 0 :(得分:1)
你应该这样做:
app.service('Session', function() {
// A service is a singleton, as in it a persistent
// object you can inject in controllers
this.foo = 'bar'; // anything on "this" is publicly available
this.createSession = function() { ... };
// you can also expose functions that you can call from the controllers
});
app.controller('Ctrl1', function($scope, Session) {
// You can inject "Session" here and use stuff you
// added on "this" inside of it
$scope.foo = Session.foo;
// you can put stuff on the controller's $scope
// and you can bind to it in your HTML by using <span>{{foo}}</span>
Session.foo = 'baz';
// you can change stuff in the service and it will be persisted
});
所以现在如果你导航到某个注入“Session”的“Ctrl2”,Session.foo
将是“baz”,而不是最初的“bar”值。