【问题标题】:JS functions in object disappears对象中的 JS 函数消失
【发布时间】:2016-02-08 10:02:14
【问题描述】:

当我最初调用这个函数时:

var session = function(){
    console.error(service.get());
    if(service.get().session === undefined){
        $localStorage.user.session = {
            timeLeft: 0,  //  Time left until a user session ends (in minutes).
            start: function(timeLeft) {
                $localStorage.user.session.timeLeft = timeLeft;
                $localStorage.user.session.interval;
            },
            stop: function(){
                $interval.cancel($localStorage.user.session.interval);
            },
            interval: $interval(function () {
                $localStorage.user.session.timeLeft -= 1;

                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 0.125 * 60000)
        };
    }

    return $localStorage.user.session;
};

来自

function sessionRestart(){
    session();
};
sessionRestart();

它使用其所有变量创建session 对象,但是当我重新加载页面时,它不会填充作为函数的变量。我该如何解决?


编辑 应用程序是AngularJS,我使用ngStorage 表示$localStorage,代码用于用户会话,可以在我的应用程序的factory 中找到。

【问题讨论】:

  • 我不知道它在 angularjs 中是如何工作的,但是在 localstorage 中你只能存储纯文本数据,所以你的 JSON 或 Object 需要被字符串化。
  • @MarcosPérezGude OP 没有直接使用 localStorage,所以没关系。
  • @dfsq 好的,我说的是I don't know how it works in angularjs,因为那是。但如果没问题,没关系:)

标签: javascript angularjs session object local-storage


【解决方案1】:

MarcosPérezGude 让我想到了解决问题的方法。哪些是将$interval 移到$localStorage 之外,这解决了我的问题。不知道为什么它不起作用。

现在的代码如下所示:

var session,
    startSession: function(timeLeft) {
        if($localStorage.user.session === undefined){
            if(timeLeft === undefined){
                timeLeft = 0;
            }

            $localStorage.user.session = {
                timeLeft: timeLeft
            };
        }

        if (session === undefined) {
            session = $interval(function () {
                $localStorage.user.session.timeLeft -= 1;

                if($localStorage.user.session.timeLeft === undefined){
                    service.stopSession();
                }

                if($localStorage.user.session.timeLeft <= 0){
                    $state.go('signin');
                }
            }, 1 * 60000);  //  Time in milliseconds. Minutes * milliseconds = total milliseconds before the interval repeats.
        }
    },
    stopSession: function() {
        $interval.cancel(session);
        session = undefined;
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    相关资源
    最近更新 更多