Using $timeout in service: this.func is not a function

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 of var
  • $timeout(function(){closeSession(this.resetUserInfo)}, sessionLength) with proper modifications to closeSession

Answers


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
    }
} 

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;

}


Need Your Help

How to change bitmap without adding another child to the stage

actionscript-3 url random bitmap addchild

I know exactly what this function is doing, however I don't know how to change it so that the 3 symbols only ever add once and only the bitmaps change. Thank you for your help! It's probably someth...