大家好! 我正在创建具有授权的应用程序。 为了在 session 期间存储用户数据,我使用这样的服务:
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;
});
在 Controller 中使用:
Session.createSession(some, params, here);
之后,它将一些数据放入 rootscope,我可以在控制台中显示它,但是当我尝试查看例如 Session.user/.level 等时,它不起作用。怎么了?
最佳答案
你应该这样做:
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
});
现在,如果您导航到某个也注入(inject)“Session”的“Ctrl2”,Session.foo
将是“baz”,而不是初始“bar”值。
关于javascript - Angularjs $rootScope 在 Controller 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560710/