我一直试图在一段时间后使用promise来结束用户会话。
问题是,每当从$ timeout触发的函数调用service中定义的函数时,该函数似乎是未定义的。我认为这是一种范围问题,但我没有设法自行解决这个问题。
app.service('sessionService', function($timeout) {
var closeSession = function() {
this.resetUserInfo()
// maybe do other things as well
}
this.start = function() {
console.log("start")
promise = $timeout(closeSession, sessionLength)
}
this.resetUserInfo = function() {
// reset session
}
}
错误:this.resetUserInfo不是函数
我尝试过的事情
this.closeSession
代替var
$timeout(function(){closeSession(this.resetUserInfo)}, sessionLength)
并对closeSession进行了适当的修改答案 0 :(得分:3)
请注意这一点。因此,您正在使用服务的范围而不是方法的范围。
app.service('sessionService', function($timeout) {
var that = this;
var closeSession = function() {
that.resetUserInfo()
// maybe do other things as well
}
this.start = function() {
console.log("start")
promise = $timeout(closeSession, sessionLength)
}
this.resetUserInfo = function() {
// reset session
}
}
答案 1 :(得分:0)
另一种方法是将resetUserInfo
作为本地函数,然后在以后附加到它。例如:
app.service('sessionService', function($timeout) {
//private definition
var resetUserInfo = function() {
}
var closeSession = function() {
resetUserInfo(); //call the private version
}
this.start = function() {
console.log("start")
promise = $timeout(closeSession, sessionLength)
}
//now expose method as public here
this.resetUserInfo = resetUserInfo;
}