javascript - Angularjs $rootScope 在 Controller 中不可见

标签 javascript angularjs authentication

大家好! 我正在创建具有授权的应用程序。 为了在 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/

相关文章:

javascript - 无法将动态数据加载到 ui-grid 下拉列表中

javascript - Vue.js 动态类

javascript - 当我自己引起 Angular $watch 事件时,如何忽略它?

java - 我应该如何在 Java 的应用程序层之间传递主题/主体/角色?

javascript - THREE.js intersects[0].object.position 始终返回 (0,0,0)

javascript - 不明白错误

angularjs - 如何在 Angular-Material Design 中打开 sideNav

javascript - Ionic Framework 无限滚动与 http 获取数据

javascript - 从 Javascript 调用网络服务

authentication - 如何使用隐式流保持用户登录?