0

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
Kelo
  • 453
  • 1
  • 3
  • 17
  • Possible duplicate of [How does the “this” keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Grundy Dec 03 '15 at 11:24
  • _this_ inside function, depends on how function calling. In your case _this_ not referse to service when function call as callback in $timeout – Grundy Dec 03 '15 at 11:27

2 Answers2

3

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
    }
} 
Simone Zandara
  • 9,401
  • 2
  • 19
  • 26
0

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;

}

Tom Makin
  • 3,203
  • 23
  • 23