问题
I've been trying to use promise to end user session after certain amount of time.
Problem is, whenever a function defined in service is called from the function triggered by $timeout, the function seems to be undefined. I think it's some kind of a scope issue, but I have not managed to fix this on my own.
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
}
}
Error: this.resetUserInfo is not a function
Things I have tried
- different ordering of functions
this.closeSession
instead ofvar
$timeout(function(){closeSession(this.resetUserInfo)}, sessionLength)
with proper modifications to closeSession
回答1:
Note this assigned to that. So you are using the scope of the service instead of the scope of the method.
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
}
}
回答2:
An alternative would be to make resetUserInfo
a local function and then attach to it this later on. For example:
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;
}
来源:https://stackoverflow.com/questions/34064666/using-timeout-in-service-this-func-is-not-a-function