【问题标题】:How to access angularjs sessionStorage value to entire project?如何访问整个项目的 angularjs sessionStorage 值?
【发布时间】:2017-06-16 11:51:19
【问题描述】:

我需要整个项目的登录值。所以我使用的是 rootScope,但如果我的页面被刷新,rootScope 值会被破坏。 因此,我使用的是 AngularJS sessionStorage 而不是 rootScope,现在值设置成功。现在我需要为整个项目使用 sessionStorage 值。

如何在任何我想要的地方使用 sessionStorage 值。我正在寻找积极的重播。

控制器

if(response.data.status != null)
{   
    scope.User=response;
    rootScope.UserId=response.data.UserId;
     $window.sessionStorage.setItem("id",response.data.UserId);
     scope.id = $window.sessionStorage.getItem("id");
    state.go("userHome");
}

谢谢你..!

【问题讨论】:

    标签: javascript angularjs session storage


    【解决方案1】:

    我会在“app.run”中的 $rootScope 上创建访问器:

    angular.module("myApp").run(['$rootScope', function($rootScope){
        var id = null;    
        $rootScope.getId = function(){
            if (!id) id = sessionStorage.getItem('id');
    
            return id;        
        };
    
        $rootScope.setId = function(userId) {
            id = userId;
            sessionStorage.setItem('id', userId);
        };
    
    }]);
    
    • 这样,您可以继续在视图中使用您的 id,您只需拨打电话即可。
    • 如果 $rootScope 没有设置值,您不会忘记检查 sessionStorage。
    • 您不必每次需要 id 时都访问 sessionStorage(查询会话存储比在堆上获取项目要慢得多)

    你只需要像下面这样使用它:

    if(response.data.status != null)
    {   
        scope.User=response;
        rootScope.setId(response.data.UserId);
        scope.id = rootScope.getId();
        state.go("userHome");
    }
    

    为了在您的视图中访问它:

    1.5+ 版本:

    您可以简单地将其绑定到 $rootscope 提供的“控制器”:

    <div>{{$root.getId()}}</div>
    

    版本 1.5-:

    只要您从未将方法或属性绑定到名为 getId$scope,以下将通过范围继承起作用(如果您不了解 Angular 中的范围继承,您真的应该花一些时间谷歌搜索它)

    <div>{{getId()}}</div>
    

    【讨论】:

    • 我可以使用 localStorage 代替 sessionStorage 吗?
    • 只需将 sessionStorage 替换为 localStorage
    • 谢谢。如何在不同页面中使用 sessionStorage 值。
    • 如果你使用 angular 1.5+,你可以像{{$root.getId()}}一样使用它
    • 我使用的是 1.4.8 angular 版本。如何使用这个版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多