当我最初调用这个函数时:
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
,该代码用于用户 session ,可以在我的应用程序中的一个工厂
。
最佳答案
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;
};
关于javascript - 对象中的JS函数消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266791/